<!--lbh  -->
<template>
  <a-spin dot class="w-full h-full" :loading="fullLoading">
    <div style="width: 100%; height: 100%; background-color: #fff; overflow-x: auto">
      <a-split :style="{
        height: '100%',
        width: '100%',
        minWidth: '500px',
        border: '1px solid var(--color-border)',
      }" v-model:size="sizes" min="500px">
        <template #first>
          <a-form :model="form" layout="inline" size="mini">
            <a-form-item label="客户">
              <a-input allow-clear class="bacClass" v-model="form.customName" :style="{ width: '150px' }"
                @press-enter="huiche" />
            </a-form-item>
            <a-form-item label="织布单号">
              <a-input allow-clear class="bacClass" v-model="form.planOrderCode" :style="{ width: '150px' }"
                @press-enter="huiche" />
            </a-form-item>
          </a-form>
          <a-spin :loading="loading" tip="加载中" dot style="height: 90%; width: 100%">
            <div class="cssToolbar">
              <!-- `${permissionStore.hasPermisson('zbdpc.pc') ? '排产' : ''}`, -->
              <Toolbar :items="[
                '委外加工',
                '手动排产',
                '自动排产',
                `${permissionStore.hasPermisson('zbdpc.wpccx') ? '查询' : ''}`,
                `${permissionStore.hasPermisson('zbdpc.wpcdc') ? '导出' : ''}`,
                `${permissionStore.hasPermisson('zbdpc.wpcdc') ? '全部导出' : ''}`,
              ]" @select="cx" @del="delWeipaichan" @paic="paic" @export="exports" @oem="sendOemOrder" @sdpc="paics"
                @zdpc="paic" @exportAll="exportAll">
              </Toolbar>
            </div>

            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
              <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :suppressDragLeaveHidesColumns="true" :rowSelection="'single'" @grid-ready="gridReady"
                @columnResized="onColumnResized" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible"
                style="height: 93%" :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList"
                :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
              <paginationCopys :page-size-options="pagingList1s" :total="total" show-total show-jumper show-page-size
                @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="size"
                :current="page" />
            </a-spin>
          </a-spin>
        </template>
        <template #second>
          <a-spin :loading="loadings" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
            <div class="iscontent2">
              <div class="iscontent21">
                <div class="divs">
                  <a-space>
                    <a-tag color="#5e8af5" style="margin-top: 7px">机台动态</a-tag>
                    <a-button type="primary" @click="LCQuery">修改机台</a-button>
                    <a-button type="primary" @click="LCQuerys">查看机台</a-button>
                  </a-space>
                  <AgGridVuesCopys :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady2"
                    style="height: 90%" :rowHeight="30" :headerHeight="30" :defaultColDef="defaultColDef"
                    class="ag-theme-alpine" :rowData="jtdtBiao" :columnDefs="tc2" @click="clickRowSelection"
                    :localeText="localeText1">
                  </AgGridVuesCopys>
                </div>
                <div class="divs">
                  <a-space>
                    <a-tag color="#5e8af5" style="margin-top: 7px">机台任务明细</a-tag>
                    <a-button type="primary" @click="rowClickeds">修改排程</a-button>
                    <a-button type="primary" @click="zjtClicks">增加机台</a-button>
                    <a-button type="primary" @click="zjtClick">转机台</a-button>
                    <a-button type="primary" @click="ztClick">暂停标识</a-button>
                  </a-space>
                  <!-- 这个表格columnDefs原本是tc3，因需求需要和上表相同，故改用tc2 -->
                  <AgGridVuesCopys :suppressCopyRowsToClipboard="true" rowSelection="single" @grid-ready="gridReady3"
                    style="height: 90%" :rowHeight="30" :headerHeight="30" :defaultColDef="defaultColDef"
                    class="ag-theme-alpine" :rowData="jtewmxBiao" :columnDefs="tableColumns4" :localeText="localeText1">
                  </AgGridVuesCopys>
                </div>
                <div class="divs">
                  <a-tag color="#5e8af5">试算明细</a-tag>
                  <AgGridVuesCopys :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady4"
                    style="height: 90%" :rowHeight="30" :headerHeight="30" :defaultColDef="defaultColDef"
                    class="ag-theme-alpine" :rowData="ssmxBiao" :columnDefs="tableColumns3" :localeText="localeText1">
                  </AgGridVuesCopys>
                </div>
                <div class="divs2">
                  <span>
                    <a-space>
                      <a-button type="primary" @click="handleTryComputed">试算</a-button>
                      <a-button type="primary" @click="sidesOks">保存</a-button>
                      <a-button type="primary" @click="sideNo1s">清空</a-button>
                    </a-space>
                  </span>
                </div>
              </div>
            </div>
          </a-spin>
        </template>
      </a-split>
    </div>
    <a-drawer style="z-index: 999" :drawer-style="{ zIndex: 999 }" ok-text="保存" cancel-text="关闭" :height="'100%'"
      :visible="pageData.showAdd" placement="bottom" unmountOnClose @cancel="handleDrawerCancel">
      <template #footer>
        <a-button type="primary" @click="sideNo1">确定</a-button>
      </template>
      <template #title>
        <span style="margin-right: 20px">{{ tititles }}</span>
        <span v-if="tititles == '手动排产' || tititles == '自动排产' || tititles == '修改机台'"
          style="margin-right: 20px">最后加载数据时间:{{ pageData.updateTime }}</span>
        <a-select v-if="tititles == '手动排产' || tititles == '自动排产' || tititles == '修改机台'" v-model="pageData.refreshStr"
          :options="pageData.refreshList" style="width: 100px; margin-right: 40px" />
        <!-- <icon-refresh
          v-if="tititles == '手动排产' || tititles == '自动排产' || tititles == '修改机台'"
          @click="handleRefresh"
        /> -->
        <el-button type="primary" @click="handleRefresh" icon="refresh"
          v-if="tititles == '手动排产' || tititles == '自动排产' || tititles == '修改机台'">刷新</el-button>
      </template>
      <div class="iscon" v-if="pageData.showAdd">
        <div class="iscontent">
          <AgGridVue :suppressCopyRowsToClipboard="true" rowSelection="multiple" style="height: 12%" :rowHeight="30"
            :defaultColDef="defaultColDefJo" class="ag-theme-alpine" :rowData="dataListssz" :columnDefs="tableColumns1"
            :localeText="localeText1" @grid-ready="gridReady5" @click="clickRowSelectionA"
            @FilterChanged="onFilterChangeds" @sortChanged="sortChanged">
          </AgGridVue>
          <a-checkbox-group :default-value="machinesIdArray" @change="macChanges">
            <div class="bg-content" v-if="pcTitels == '自动排产'">
              <!-- @change="changeId" -->
              <span class="bg-contentA" style="display: flex">
                <a-tag id="aTag" color="#5e8af5">推荐机台 </a-tag>
                <div v-for="(item, index) in machineIDs2">
                  <div :class="item.state == 0 ? 'lvClass' : item.state == 1 ? 'huClass' : 'wxClass'">
                    <a-checkbox v-model="item.id" :value="item.id">
                      <span>
                        <a-popover title="详情">
                          <a-button type="primary" shape="round" size="mini">{{ item.machineCode }}-机台明细</a-button>
                          <template #content>
                            <p>机台类型：{{ item.machineTypeName }}</p>
                            <p>区域：{{ item.areaName }}</p>
                            <p>织布单号个数：{{ item.incompleteNum }}</p>
                            <p>织布单号总量：{{ item.incompleteWeight }}</p>
                          </template>
                        </a-popover>
                      </span>
                    </a-checkbox>
                  </div>
                </div>
              </span>
            </div>
            <a-tabs :lazy-load="true" :active-key="tabKey" @change="tabchange" style="width: 100%; height: 88%">
              <template #extra>
                <a-space style="margin-left: 10px">
                  <div style="width: 30px; height: 30px; background-color: #9fa2a8"></div>
                  <span>未启动</span>
                  <div style="width: 30px; height: 30px; background-color: #ccc"></div>
                  <span>待单</span>
                  <div style="width: 30px; height: 30px; background-color: #ebf13fe1"></div>
                  <span>待纱</span>
                  <div style="width: 30px; height: 30px; background-color: #c1c460e1"></div>
                  <span>洗转机</span>
                  <div style="width: 30px; height: 30px; background-color: #1c9a13"></div>
                  <span>运行</span>
                  <div style="width: 30px; height: 30px; background-color: #2786cf"></div>
                  <span>暂停</span>
                  <div style="width: 30px; height: 30px; background-color: #cf2762"></div>
                  <span>维修</span>
                  <div style="width: 30px; height: 30px; background-color: #c127cf"></div>
                  <span>保养</span>
                  <a-button type="primary" @click="selectClickAll">查看所有机台</a-button>
                </a-space>
              </template>
              <a-tab-pane style="overflow: auto; height: 100%" :key="floorInfo.floorName" :title="floorInfo.floorName"
                v-for="(floorInfo, index) in pageData.clothListr">
                <div class="layoutBox">
                  <div v-if="ArrayList.find((i: any) => i.story == floorInfo.floorName)"
                    style="width: 100%; height: 100%">
                    <grid-layout v-for="item in ArrayList.filter((i: any) => i.story == floorInfo.floorName)"
                      :ref="'gridlayoutRef' + floorInfo.floorName" :layout.sync="item.detail.layout"
                      :col-num="item.detail.form.long" :row-height="item.detail.form.heigt" :responsive="false"
                      :vertical-compact="false" :prevent-collision="false" :use-css-transforms="false"
                      :is-draggable="false" :is-resizable="false" class="grid_cals2">
                      <div>
                        <grid-item style="zoom: 1" v-for="item2 in item.detail.backgroundData" :x="item2.x" :y="item2.y"
                          :w="item2.w" :h="item2.h" :i="item2.i" :key="item2.i" :is-draggable="false"
                          :is-resizable="false" class="grid-item" />
                      </div>
                      <!-- :class="{ borderClass: item.isBooval }" -->
                      <grid-item :key="item3.i" v-for="item3 in item.detail.layout" :x="item3.x" :y="item3.y"
                        :w="item3.w" :h="item3.h" :i="item3.i"
                        :style="{ background: getColor(item3.text, item3.type), zoom: 1 }">
                        <div class="clmodule" @dblclick="getEdit(item3)">
                          <div v-if="item3.text == '机台'" class="machine-item" style="height: 80%">
                            <a-checkbox v-if="item3.type != 0" v-model="item3.id" :value="item3.id"
                              style="position: absolute; right: -15px; bottom: 0"></a-checkbox>
                            <div class="song-9">{{ item3.planOrderCode }}</div>
                            <div class="song-9">{{ item3.greyCode }}</div>
                            <div class="song-9">{{ item3.workDrum }}</div>
                            <div class="song-9">{{ item3.colorName }}</div>
                            <div class="song-9">{{ item3.machineName }}</div>
                          </div>
                          <div v-if="item3.text == '机台'" :style="{
                            fontFamily: 'sans-serif',
                            fontSize: '12px',
                            wordBreak: 'break-all',
                            width: '100%',
                            height: '20%',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            overflow: 'hidden',
                            fontWeight: 'bold',
                          }">
                            {{ item3.machineCode }}
                          </div>
                          <div v-if="item3.text != '机台'" style="width: 100%; text-align: center">
                            {{ item3.text }}
                          </div>
                        </div>
                      </grid-item>
                    </grid-layout>
                  </div>
                  <div style="width: 100%; height: 100%" v-else>
                    <div style="
                        width: 100%;
                        height: 100%;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        position: absolute;
                      ">
                      <a-spin dot v-if="floorInfo.loadingState" />
                      <div v-if="!floorInfo.loadingState">暂无数据！</div>
                    </div>
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="888" title="机台明细" style="height: 100%">
                <div style="height: 600px; width: 100%; overflow: auto">
                  <encapsulation-agrid ref="table1Ref" :configaggrid="configaggrid"></encapsulation-agrid>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-checkbox-group>
        </div>
      </div>
      <!-- </a-modal> -->
    </a-drawer>

    <a-drawer style="z-index: 999" :drawer-style="{ zIndex: 999 }" ok-text="保存" cancel-text="关闭" :height="'100%'"
      :visible="pageData.showAdd2" placement="bottom" unmountOnClose @cancel="handleDrawerCancel">
      <template #footer>
        <a-button type="primary" @click="sideNo1">确定</a-button>
      </template>
      <template #title>
        <span style="margin-right: 20px">查看机台</span>
        <span style="margin-right: 20px">最后加载数据时间:{{ pageData.updateTime }}</span>
        <a-select v-model="pageData.refreshStr" :options="pageData.refreshList"
          style="width: 100px; margin-right: 40px" />
        <!-- <icon-refresh @click="handleRefresh2" /> -->
        <el-button type="primary" @click="handleRefresh2" icon="refresh">刷新</el-button>
      </template>
      <div class="iscon">
        <div class="iscontent">
          <a-checkbox-group style="" :default-value="machinesIdArray2" @change="macChangess">
            <a-tabs :lazy-load="true" :active-key="tabKey2" @change="tabchange2" style="width: 100%; height: 100%">
              <template #extra>
                <a-space style="margin-left: 10px">
                  <div style="width: 30px; height: 30px; background-color: #9fa2a8"></div>
                  <span>未启动</span>
                  <div style="width: 30px; height: 30px; background-color: #ccc"></div>
                  <span>待单</span>
                  <div style="width: 30px; height: 30px; background-color: #ebf13fe1"></div>
                  <span>待纱</span>
                  <div style="width: 30px; height: 30px; background-color: #c1c460e1"></div>
                  <span>洗转机</span>
                  <div style="width: 30px; height: 30px; background-color: #1c9a13"></div>
                  <span>运行</span>
                  <div style="width: 30px; height: 30px; background-color: #2786cf"></div>
                  <span>暂停</span>
                  <div style="width: 30px; height: 30px; background-color: #cf2762"></div>
                  <span>维修</span>
                  <div style="width: 30px; height: 30px; background-color: #c127cf"></div>
                  <span>保养</span>
                  <a-button type="primary" @click="selectClickAll">查看所有机台</a-button>
                </a-space>
              </template>
              <a-tab-pane style="overflow: auto; height: 100%" :key="floorInfo.floorName" :title="floorInfo.floorName"
                v-for="(floorInfo, index) in pageData.clothListr">
                <div class="layoutBox">
                  <div v-if="ArrayList2.find((i: any) => i.story == floorInfo.floorName)"
                    style="width: 100%; height: 100%">
                    <grid-layout v-for="item in ArrayList2.filter((i: any) => i.story == floorInfo.floorName)"
                      :ref="'gridlayoutRef2' + floorInfo.floorName" :layout.sync="item.detail.layout"
                      :col-num="item.detail.form.long" :row-height="item.detail.form.heigt" :responsive="false"
                      :vertical-compact="false" :prevent-collision="false" :use-css-transforms="false"
                      :is-draggable="false" :is-resizable="false" class="grid_cals2">
                      <div>
                        <grid-item style="zoom: 1" v-for="item2 in item.detail.backgroundData" :x="item2.x" :y="item2.y"
                          :w="item2.w" :h="item2.h" :i="item2.i" :key="item2.i" :is-draggable="false"
                          :is-resizable="false" class="grid-item" />
                      </div>
                      <!-- :class="{ borderClass: item.isBooval }" -->
                      <grid-item :key="item3.i" v-for="item3 in item.detail.layout" :x="item3.x" :y="item3.y"
                        :w="item3.w" :h="item3.h" :i="item3.i"
                        :style="{ background: getColor(item3.text, item3.type), zoom: 1 }">
                        <div class="clmodule" @dblclick="getEdit(item3)">
                          <div v-if="item3.text == '机台'">
                            <a-checkbox v-if="item3.type != 0" v-model="item3.id"
                              :value="item3.id + '/' + item3.machineCode"
                              style="position: absolute; right: -15px; bottom: 0"></a-checkbox>
                            <a-popover title="详情" style="text-align: center">
                              <a-button type="text" :style="{ color: '#000', width: '100%', padding: '0' }" size="mini">
                                <div style="
                                    font-size: 9px !important;
                                    width: 100% !important;
                                    white-space: normal !important;
                                    word-break: break-all !important;
                                  ">
                                  {{ item3.machineName }}</div>
                              </a-button>
                              <template #content>
                                <p>物料大类：{{ item3.majorCategory }}</p>
                                <p>物料中类：{{ item3.middleCategory }}</p>
                                <p>物料小类：{{ item3.subCategory }}</p>
                                <p>物料编号：{{ item3.materialCode }}</p>
                                <p>物料名称：{{ item3.materialName }}</p>
                                <p>规格：{{ item3.specification }}</p>
                                <p>机台编号：{{ item3.machineCode }}</p>
                              </template>
                            </a-popover>
                          </div>
                          <div v-if="item3.text == '机台'" :style="{
                            wordBreak: 'break-all',
                            width: '100%',
                            textAlign: 'center',
                            overflow: 'hidden',
                            fontWeight: '600',
                          }">
                            {{ item3.machineCode }}
                          </div>
                          <div v-if="item3.text != '机台'" style="width: 100%; text-align: center">
                            {{ item3.text }}
                          </div>
                        </div>
                      </grid-item>
                    </grid-layout>
                  </div>
                  <div style="width: 100%; height: 100%" v-else>
                    <div style="
                        width: 100%;
                        height: 100%;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        position: absolute;
                      ">
                      <a-spin dot v-if="floorInfo.loadingState" />
                      <div v-if="!floorInfo.loadingState">暂无数据！</div>
                    </div>
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="888" title="机台明细" style="height: 100%">
                <div style="height: 600px; width: 100%; overflow: auto">
                  <encapsulation-agrid ref="table1Ref" :configaggrid="configaggrid"></encapsulation-agrid>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-checkbox-group>
        </div>
      </div>
      <!-- </a-modal> -->
    </a-drawer>

    <a-modal :width="1200" v-model:visible="visible" :on-before-ok="handleOk" @cancel="handleCancel">
      <template #title> 机台排产详情 </template>
      <div class="jitaipaic">
        <div><span>最大可排产天数{{ maxData }}</span></div>
        <div class="jitaipaic1"><span>计划重量{{ orderWeight }}KG</span></div>
      </div>
      <a-table :scrollbar="true" sticky-header size="mini" :columns="columns" :data="data" :pagination="false"
        :style="{ height: '500px' }">
        <template v-for="(item, index) in columns" #[item.slotName]="{ record }">
          <div>
            <a-input-number class="bacClass" allow-clear v-model="record[item.slotName]">
              <template #append> KG </template>
            </a-input-number>
          </div>
        </template>
      </a-table>
    </a-modal>

    <a-modal ok-text="关闭" v-model:visible="visibleSelectAll" @ok="visibleSelectAll = false" fullscreen
      :hide-cancel="true" :closable="false">
      <template #title>
        <div style="width: 80%">所有楼层</div>
        <a-space style="margin-left: 10px">
          <div style="width: 30px; height: 30px; background-color: #9fa2a8"></div>
          <span style="font-size: 12px !important">未启动</span>
          <div style="width: 30px; height: 30px; background-color: #ccc"></div><span
            style="font-size: 12px !important">待单</span>
          <div style="width: 30px; height: 30px; background-color: #ebf13fe1"></div><span
            style="font-size: 12px !important">待纱</span>
          <div style="width: 30px; height: 30px; background-color: #c1c460e1"></div>
          <span style="font-size: 12px !important">洗转机</span>
          <div style="width: 30px; height: 30px; background-color: #1c9a13"></div>
          <span style="font-size: 12px !important">运行</span>
          <div style="width: 30px; height: 30px; background-color: #2786cf"></div><span
            style="font-size: 12px !important">暂停</span>
          <div style="width: 30px; height: 30px; background-color: #cf2762"></div><span
            style="font-size: 12px !important">维修</span>
          <div style="width: 30px; height: 30px; background-color: #c127cf"></div>
          <span style="font-size: 12px !important">保养</span>
        </a-space>
      </template>
      <a-card :style="{ width: '100%', height: '82%', marginBottom: '10px' }" :title="z.story"
        v-for="(z, index) in ArrayList" hoverable>
        <div class="layoutBoxs">
          <grid-layout :layout.sync="z.detail.layout" :col-num="z.detail.form.long" :row-height="z.detail.form.heigt"
            :responsive="false" :vertical-compact="false" :prevent-collision="false" :use-css-transforms="false"
            :is-draggable="false" :is-resizable="false" class="grid_cals2">
            <div>
              <grid-item style="zoom: 1" v-for="item in z.detail.backgroundData" :x="item.x" :y="item.y" :w="item.w"
                :h="item.h" :i="item.i" :key="item.i" :is-draggable="false" :is-resizable="false" class="grid-item" />
            </div>
            <!-- :class="{ borderClass: item.isBooval }" -->
            <grid-item :key="item.i" v-for="item in z.detail.layout" :x="item.x" :y="item.y" :w="item.w" :h="item.h"
              :i="item.i" :style="{ background: getColor(item.text, item.type), zoom: 1 }">
              <div class="clmodule" @dblclick="getEdit(item)" :class="{ borderClass: item.isBooval }">
                <div v-if="item.text == '机台'" style="width: 100%; text-align: center">
                  <a-popover title="详情">
                    <a-button type="text" :style="{ color: '#000' }" size="mini">
                      <div style="
                          font-size: 9px !important;
                          width: 50px !important;
                          white-space: normal !important;
                        ">
                        {{ item.machineName }}</div>
                    </a-button>
                    <template #content>
                      <p>物料大类：{{ item.majorCategory }}</p>
                      <p>物料中类：{{ item.middleCategory }}</p>
                      <p>物料小类：{{ item.subCategory }}</p>
                      <p>物料编号：{{ item.materialCode }}</p>
                      <p>物料名称：{{ item.materialName }}</p>
                      <p>规格：{{ item.specification }}</p>
                      <p>机台编号：{{ item.machineCode }}</p>
                    </template>
                  </a-popover>
                </div>
                <div v-if="item.text == '机台'" :style="{
                  wordBreak: 'break-all',
                  width: '100%',
                  textAlign: 'center',
                  fontWeight: '600',
                }">
                  {{ item.machineCode }}
                </div>
                <div v-if="item.text != '机台'" style="width: 100%; text-align: center">{{ item.text }}
                </div>
              </div>
            </grid-item>
          </grid-layout>
        </div>
      </a-card>
    </a-modal>
    <div v-show="false">
      <EmbroideryList2></EmbroideryList2>
    </div>
    <a-modal v-model:visible="visiblezz" :hide-title="true" @cancel="visible = false" :footer="false">
      <a-space>
        <el-button type="primary" @click="tjdd">停机等待</el-button>
        <el-button type="primary" @click="ztzzxyd">暂停转做下单</el-button>
      </a-space>
    </a-modal>

    <el-dialog v-model="dblclicksShowA2" :width="1080" :height="800" :title="titels" append-to-body draggable
      :close-on-click-modal="false">
      <div v-if="titels == '增加机台详情'" style="
          width: 100%;
          display: flex;
          justify-content: flex-end;
          position: absolute;
          top: 47px;
          right: 30px;
        ">
        <el-button type="primary" @click="addMachine">增加机台</el-button>
      </div>
      <div v-if="titels == '增加机台详情'" style="width: 100%; height: 500px; overflow: auto; margin-top: 25px">
        <encapsulation-agrid ref="table2Ref" :configaggrid="configTable2"></encapsulation-agrid>
      </div>
      <AgGridVuesCopys v-if="titels == '转机台详情'" :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true" @grid-ready="gridReadyA2" style="height: 60vh; width: 100%"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="tcA2DataList" :columnDefs="tc2"
        :localeText="localeText1"></AgGridVuesCopys>
      <!-- 这个表格本身:columnDefs="tcA2" -->
      <paginationCopys v-if="titels == '转机台详情'" :page-size-options="pagingList1s" :total="pageConfig.zjtTotal"
        show-total show-jumper show-page-size @change="handleZjtPageChange" @page-size-change="zjtChange"
        style="justify-content: center" :page-size="pageConfig.zjtSize" :current="pageConfig.zjtPage" />
      <el-dialog v-model="innerDialogVisible" :width="1080" :height="800" title="机台明细" align-center append-to-body
        :close-on-click-modal="false">
        <div style="width: 455px; display: flex; justify-content: space-between; margin-bottom: 10px">
          <div class="params-content">
            <a-form :model="innerForm" layout="inline" size="mini">
              <a-form-item label="机台号">
                <a-input allow-clear class="bacClass" v-model="innerForm.machineCode" />
              </a-form-item>
            </a-form>
          </div>
          <div class="button-content" style="position: absolute; right: 25px">
            <el-button size="small" type="primary" @click="searchMachine">查询</el-button>
          </div>
        </div>
        <div style="width: 100%; height: 500px; overflow: auto">
          <encapsulation-agrid ref="table3Ref" :configaggrid="configTable3"></encapsulation-agrid>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="innerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="innerDialogConfirm"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="addMachineMessageVisible" title="提示" width="500" center align-center append-to-body
        :close-on-click-modal="false">
        <span>
          {{ addMachineMessageboxMsg }}
        </span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addMachineMessageVisible = false">取消</el-button>
            <el-button type="primary" @click="msgBoxConfirm"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="() => (dblclicksShowA2 = false)">关闭</el-button>
          <el-button type="primary" @click="saveZjt" :loading="saveZjtLoading"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dblclicksShowA1" :width="1080" :height="800" title="修改排程" draggable>
      <div class="insert-order-box">
        <el-button type="primary" @click="insertOrder">插单</el-button>
      </div>
      <AgGridVuesCopys :rowDragManaged="true" :animateRows="true" :rowHeight="33" :headerHeight="33"
        :suppressCopyRowsToClipboard="true" :suppressDragLeaveHidesColumns="true" rowSelection="single"
        @grid-ready="gridReady2AF" style="height: 500px" :defaultColDef="defaultColDef2" class="ag-theme-alpine"
        :rowData="agClousData2" :columnDefs="agClous2" :localeText="localeText1" @rowDragEnd="rowDragEnd">
      </AgGridVuesCopys>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="() => (dblclicksShowA1 = false)">关闭</el-button>
          <el-button type="primary" @click="zjtbc"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="提示" v-model="switchMachineSaveModal" width="20%" top="45vh" :close-on-click-modal="false"
      :show-close="false" center append-to-body>
      <span>{{ switchMachineSaveModalMessage }}</span>
      <template #footer>
        <el-button @click="switchMachineSaveModal = false" :disabled="fullLoading1">取 消</el-button>
        <el-button type="primary" @click="handleSwitchMachineSaveOk" :loading="fullLoading1">确 定</el-button>
      </template>
    </el-dialog>
  </a-spin>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted, watch, getCurrentInstance } from 'vue'
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from '@/hooks/table'
import Toolbar from '@/components/Toolbar.vue'
import { post } from '@/api/http'
import { Message } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'
import { ValueData } from '@arco-design/web-vue/es/_utils/types'
import { AgGridVue } from 'ag-grid-vue3'
import dayjs from 'dayjs'
import { localeText } from '@/api/aggridZw'
import { useRoute, useRouter } from 'vue-router'
import emitter from '@/hooks/useEventBus'
import usePermission from '@/store/modules/permission'
import EmbroideryList from '@/components/product/ProductManagement/EmbroideryList.vue'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import GanttChartChart from '@/views/YarnStrippings/GanttChartChart.vue'
import EmbroideryList2 from '@/components/processrowfactory/components/EmbroideryList2.vue'
import filedownload from 'js-file-download'
import { fi } from 'element-plus/es/locale'
import { ElMessage } from 'element-plus'
const instance: any = getCurrentInstance()
const switchMachineSaveModal = ref(false)
const switchMachineSaveModalMessage = ref('')
const permissionStore = usePermission()
const pagingList1s: any = ref(pagingList)
const router = useRouter()
const fullLoading = ref(false)
const fullLoading1 = ref(false)
const innerDialogVisible = ref(false)
const innerForm = reactive({
  machineCode: '',
})
const pageConfig = reactive({
  zjtTotal: 0,
  zjtSize: 10,
  zjtPage: 1,
})
const sizes = ref(0.5)
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}

const gridOption3 = ref()
const gridReady3 = (params: any) => {
  gridOption3.value = params.api
}

const gridOption4 = ref()
const gridReady4 = (params: any) => {
  gridOption4.value = params.api
}

const gridOption5 = ref()
const gridReady5 = (params: any) => {
  gridOption5.value = params.api
}

const onFilterChanged = (params: any) => {
  let dataList: any = []

  params.api.forEachNodeAfterFilter((row: any, index: number) => {
    dataList.push(row.data)
  })

  params.api.forEachNode((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
  });

  let yourColumnDefs = gridOption5.value.getColumnDefs()
  // 找到行号列的配置对象
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  // 如果找到了行号列的配置对象，则更新其 headerValue 属性为最大的 ROW_INDEX
  if (rowIndexColumn) {
    rowIndexColumn.headerName = dataList.length;
    gridOption5.value.setColumnDefs(yourColumnDefs)
  }
}

const sortChanged = (params) => {
  let dataList = [];
  let maxRowIndex = 0;

  // 遍历过滤后的节点，更新行号并收集数据
  params.api.forEachNodeAfterFilter((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
    dataList.push(node.data);
    maxRowIndex = Math.max(maxRowIndex, rowIndex);
  });

  // 更新表头的最大行号
  let yourColumnDefs = gridOption5.value.getColumnDefs();
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  if (rowIndexColumn) {
    rowIndexColumn.headerName = maxRowIndex;
    gridOption5.value.setColumnDefs(yourColumnDefs);
  }
};

const table1Ref = ref<any>(null)
const tableColumns5 = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: '公司',
    field: 'firm',
    width: 150,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 150,
  },
  {
    headerName: '位置号',
    field: 'coordinate',
    width: 150,
  },
  {
    headerName: '生产单号',
    field: 'weavingCode',
    width: 150,
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 150,
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 150,
  },
  {
    headerName: '织单机型',
    field: 'orderMachineType',
    width: 150,
  },
  {
    headerName: '设备机型',
    field: 'machineTypeName',
    width: 150,
  },
  {
    headerName: '织单针寸数',
    field: 'workDrum',
    width: 150,
  },
  {
    headerName: '纱长',
    field: 'yarnLength',
    width: 150,
  },
  {
    headerName: '颜色',
    field: 'colorName',
    width: 150,
  },
  {
    headerName: '原料信息',
    field: 'rawInfo',
    width: 150,
  },
  {
    headerName: '客户名称',
    field: 'customName',
    width: 150,
  },
  {
    headerName: '机台针寸数',
    field: 'machineWorkDrum',
    width: 150,
  },
  {
    headerName: '主推商品号',
    field: 'productColthCode',
    width: 150,
  },
  {
    headerName: '机台预计完成时间',
    field: 'finishTime',
    width: 150,
  },
  {
    headerName: '机台状态',
    field: 'machineState',
    width: 150,
  },
  {
    headerName: '机台负荷',
    field: 'machineInfo',
    width: 150,
    valueGetter: (params: any) => {
      return params.data.machineInfo == 0
        ? '空闲'
        : params.data.machineInfo == 1
          ? '正常'
          : params.data.machineInfo == 2
            ? '饱和'
            : params.data.machineInfo == 3
              ? '负荷'
              : params.data.machineInfo == 4
                ? '待单'
                : ''
    },
  },
]
let configaggrid = ref({
  url: '', //接口路径
  queryData: {
    //接口参数
  },
  paginationShow: false, //分页是否显示
  invokeiIterface: false, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns5,
  fileName: 'zbdNopc-1',
})
const table2Ref = ref<any>(null)
const tableColumns6 = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: '织布单号',
    field: 'planOrderCode',
    width: 150,
  },
  {
    headerName: '生产单号',
    field: 'weavingCode',
    width: 150,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 150,
  },
  {
    headerName: '未生产重量',
    field: 'productWeight',
    width: 150,
  },
  {
    headerName: '预计开始时间',
    field: 'startTime',
    width: 150,
  },
  {
    headerName: '实际开始时间',
    field: 'actualStartTime',
    width: 150,
  },
  {
    headerName: '预计完成时间',
    field: 'pEndTime',
    width: 150,
  },
  {
    headerName: '实际完成时间',
    field: 'actualEndTime',
    width: 150,
  },
  {
    headerName: '生产状态',
    field: 'productionState',
    width: 150,
    pinned: 'right',
    valueGetter: (params: any) => {
      return params.data.productionState == 0
        ? '等待'
        : params.data.productionState == 1
          ? '生产中'
          : params.data.productionState == 2
            ? '完成'
            : params.data.productionState == 3
              ? '暂停'
              : ''
    },
  },
]
let configTable2 = ref({
  url: '', //接口路径
  queryData: {
    //接口参数
  },
  paginationShow: false, //分页是否显示
  invokeiIterface: false, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns6,
  fileName: 'zbdNopc-6',
})
const table3Ref = ref<any>(null)
const tableColumns7 = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    maxWidth: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
    resizable: false,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 150,
  },
  {
    headerName: '楼层',
    field: 'areaName',
    width: 150,
  },
  {
    headerName: '针寸数',
    field: 'workDrum',
    width: 150,
  },
  {
    headerName: '机台状态',
    field: 'machineState',
    width: 150,
    pinned: 'right',
  },
]
let configTable3 = ref({
  url: '', //接口路径
  queryData: {
    //接口参数
  },
  paginationShow: false, //分页是否显示
  invokeiIterface: false, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns5,
  fileName: 'zbdNopc-7',
})
const addMachineMessageVisible = ref(false)
const addMachineMessageboxMsg = ref('')
const msgBoxConfirm = () => {
  zjJt()
}
const searchMachine = async () => {
  try {
    const { planOrderCode } = gridOption3.value.getSelectedRows()[0]
    const res = await post({
      url: 'product/statement/getMachineDetail',
      data: {
        page: 1,
        size: 100000,
        noState: 100,
        planOrderCode,
        machineCode: innerForm.machineCode,
      },
    })
    if (res.code == 200) {
      table3Ref.value.setdataListIterface(res.data.list)
    } else {
      Message.error(res.message)
    }
  } catch (e) {
    console.log(e)
  }
}
const addMachine = async () => {
  try {
    //每次点击增加机台 都要先记录当前已有的机台号 避免重复
    const addedMachineCodes = table2Ref.value.getListData().map((item: any) => item.machineCode)
    const { planOrderCode } = gridOption3.value.getSelectedRows()[0]
    const res = await post({
      url: 'product/statement/getMachineDetail',
      data: {
        page: 1,
        size: 100000,
        noState: 100,
        planOrderCode,
      },
    })
    if (res.code == 200) {
      const filterData = res.data.list.filter(
        (item: any) => !addedMachineCodes.includes(item.machineCode)
      )
      innerDialogVisible.value = true
      nextTick(() => {
        table3Ref.value.setdataListIterface(filterData)
      })
    } else {
      Message.error(res.message)
    }
  } catch (e) {
    console.log(e)
  }
}
const innerDialogConfirm = () => {
  const { planOrderCode } = gridOption3.value.getSelectedRows()[0]
  const mapRow = table3Ref.value.getSelectedRows().map((item: any) => {
    return {
      planOrderCode,
      machineCode: item.machineCode,
      areaName: item.areaName,
      coordinate: item.coordinate,
      machineName: item.machineName,
      machineTypeName: item.machineTypeName,
    }
  })
  const table2Row = table2Ref.value.getListData()
  table2Row.push(...mapRow)
  table2Ref.value.setdataListIterface(table2Row)
  innerDialogVisible.value = false
}
const { selectedRowKeys } = useRowSelection()
const selectedKeys2: any = ref()
const clickRowSelection = () => {
  selectedKeys2.value = gridOption2.value.getSelectedRows().map((res: any) => res.id)
}
const objArray: any = ref([])
watch(
  () => selectedKeys2.value,
  (newData, oldData) => {
    objArray.value = []
    jtdtBiao.value.forEach((o: any) => {
      if (selectedKeys2.value.includes(o.id)) {
        objArray.value.push(o)
      }
    })
    post({
      url: 'planSingle/planSchedul/getScheduleInfoByMachineAll',
      data: objArray.value,
    }).then((res: any) => {
      if (res.code == 200) {
        jtewmxBiao.value = res.data
        // if(res.data.length == 0){
        //     Message.warning('无任务明细')
        // }else if(objArray.length == 0){
        //     Message.warning('请勾选机台动态表')
        // }
      } else {
        Message.error(res.message)
      }
    })
  }
)

const ssmxBiao2: any = ref([])
const handleDrawerCancel = () => {
  pageData.showAdd = false
  pageData.showAdd2 = false
  tempIds = null
  tabKey.value = pageData.clothListr[0].floorName
  tabKey2.value = pageData.clothListr[0].floorName
  pageData.refreshStr = '全部'
  // pageData.clothListr.forEach((item: any) => (item.loadingState = true))
  pageData.clothListr = []
  ArrayList.value = []
  ArrayList2.value = []
  yesAndNoP.value = false
}
let initRowData: any = [] //在渲染页面的初始拿到初始行数据
let tempPaicsMachineData: any = [] //用于中转手动排产试算传参的变量（machineData）
//点击手动排产/自动排产 确定按钮之后 加载试算明细表格的方法
const shiSuans = () => {
  // if (!yesAndNoP.value) {
  //   Message.error('无排产订单！')
  //   return
  // }
  let ssmxBiao3: any = []
  for (let i = 0; i < ssmxBiao.value.length; i++) {
    if (ssmxBiao.value[i].alreadyWeight != ssmxBiao2.value[i].alreadyWeight) {
      ssmxBiao3.push(ssmxBiao.value[i])
    }
  }
  let machineData: any = []
  tempPaicsMachineData = []
  jtdtBiao.value.forEach((o: any) => {
    machineData = machineData.concat(
      trialMachines.filter((o1: any) => o1.machineCode === o.machineCode)
    )
    tempPaicsMachineData = tempPaicsMachineData.concat(
      trialMachines.filter((o1: any) => o1.machineCode === o.machineCode)
    )
  })
  if (schedulingType.value == '手动排产') {
    post({
      url: 'planSingle/planSchedul/getScheduleCalculate',
      data: {
        ...dataListssz.value[0],
        weavDeliveryDate: dataListssz.value[0].lastDeliveryTime,
        ...dataListss,
        storey: queryData.storey,
        machine: machineData,
        taskDetail: jtewmxBiao.value,
        calculateData: ssmxBiao3,
        oldInfos: ssmxBiao.value,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        //拷贝一份出来
        initRowData = JSON.parse(JSON.stringify(res.data))
        ssmxBiao.value = res.data
        ssmxBiao2.value = JSON.parse(JSON.stringify(res.data))
        setTimeout(() => {
          gridOption4.value.setRowData(res.data)
        }, 0)
      } else {
        Message.error(res.message)
      }
    })
  } else if (schedulingType.value == '自动排产' || schedulingType.value == '修改机台') {
    //修改了分配数量的行数组
    const changeArr: any = []
    //初始的行
    const nowRowData: any = []
    gridOption4.value.forEachNode((node: any) => {
      nowRowData.push(node.data)
    })
    //找到了修改了分配重量的行
    initRowData.forEach((item: any) => {
      const obj = nowRowData.find((item2: any) => item2.weaveingCode == item.weaveingCode)
      if (obj && obj.alreadyWeight != item.alreadyWeight) {
        changeArr.push(obj)
      }
    })
    post({
      url: 'planSingle/planSchedul/getScheduleCalculate',
      data: {
        ...dataListssz.value[0],
        weavDeliveryDate: dataListssz.value[0].lastDeliveryTime,
        ...dataListss,
        storey: queryData.storey,
        machine: machineData,
        taskDetail: jtewmxBiao.value,
        calculateData: changeArr,
        oldInfos: ssmxBiao.value,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        ssmxBiao.value = res.data
        ssmxBiao2.value = JSON.parse(JSON.stringify(res.data))
        setTimeout(() => {
          gridOption4.value.setRowData(res.data)
        }, 0)
        Message.success('试算成功')
      } else {
        Message.error(res.message)
      }
    })
  }
}
//点击试算按钮 重新渲染表格数据的方法
const handleTryComputed = async () => {
  if (schedulingType.value == '手动排产') {
    try {
      //修改了分配数量的行数组
      const changeArr: any = []
      //初始的行
      const nowRowData: any = []
      gridOption4.value.forEachNode((node: any) => {
        nowRowData.push(node.data)
      })
      //找到了修改了分配重量的行
      initRowData.forEach((item: any) => {
        const obj = nowRowData.find((item2: any) => item2.weaveingCode == item.weaveingCode)
        if (obj && obj.alreadyWeight != item.alreadyWeight) {
          changeArr.push(obj)
        }
      })
      const res = await post({
        url: 'planSingle/planSchedul/getScheduleCalculate',
        data: {
          ...dataListssz.value[0],
          weavDeliveryDate: dataListssz.value[0].lastDeliveryTime,
          ...dataListss,
          storey: queryData.storey,
          machine: tempPaicsMachineData,
          taskDetail: jtewmxBiao.value,
          calculateData: changeArr,
          oldInfos: ssmxBiao.value,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          // ssmxBiao.value = res.data
          ssmxBiao2.value = JSON.parse(JSON.stringify(res.data))
          setTimeout(() => {
            gridOption4.value.setRowData(res.data)
          }, 0)
          Message.success('试算成功')
        } else {
          Message.error(res.message)
        }
      })
    } catch (e) {
      console.log(e)
    }
  } else if (schedulingType.value == '自动排产' || schedulingType.value == '查看机台') {
    shiSuans()
  }
}
onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  doRefresh()
  post({
    url: 'planSingle/planSchedul/upRedis',
  })
})

// let rangeValue = ref()
const total = ref(10)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

function doRefresh() {
  pageData.pageLoading = true
  updateGridState01()
  post({
    url: 'planSingle/planSchedul/getPageInfo',
    data: {
      page: page.value,
      size: size.value,
      deleteState: 0,
      schedulState: 0,
      customName: form.customName,
      planOrderCode: form.planOrderCode,
      greyCode: form.greyCode,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        pageData.refreshList = pageData.refreshList.slice(0, 1)
        // lc()
        gridOption.value.setRowData(data.list)
        table.handleSuccess(data.list)
        emitter.emit('bcCx')
        total.value = data.total
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const exportAll = () => {
  post({
    url: 'planSingle/planSchedul/excelAllPlanSchedul',
    data: {
      deleteState: 0,
      schedulState: 0,
      customName: form.customName,
      planOrderCode: form.planOrderCode,
      greyCode: form.greyCode,
    },
    responseType: 'blob',
  }).then((res) => {
    filedownload(res, '织布单排产列表.xlsx')
  })
}
const checkboxs = () => {
  Message.error('请先选择时间')
}

const cx = () => {
  page.value = 1
  doRefresh()
}
const handleSelect = (key: any) => {
  let ids = 0
  switch (key) {
    case '紧急':
      ids = 2
      break
    case '急':
      ids = 1
      break
    case '正常':
      ids = 0
      break
    default:
      break
  }
  post({
    url: 'planSingle/planSchedul/update',
    data: [
      {
        id: Number(selectIsh.id),
        planOrderState: Number(ids),
      },
    ],
  }).then((res: any) => {
    if (res.code === 200) {
      doRefresh()
      Message.success('修改成功')
    } else {
      Message.error(res.message)
    }
  })
}
let selectIsh: {
  id: any
} = {
  id: '',
}
//btn获取当前行信息
const handleSelects = (key: any) => {
  selectIsh = key
}
const pagination = usePagination(doRefresh)
const rowKey = useRowKey('id')
const queryData = reactive({
  firm: '',
  clothType: '',
  storey: '',
})
const delWeipaichan = () => {
  let isArray: any[] = []
  gridOption.value.getSelectedRows().forEach((item: any) => {
    isArray.push(item.id)
  })
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      // console.log(selectedRowKeys.value.values)
      post({
        url: 'planSingle/planSchedul/delete',
        data: isArray,
      }).then(({ code, data }: any) => {
        if (code === 200) {
          doRefresh()
          selectedRowKeys.value = []
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
        } else {
          Message.success({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
}

const machinesIdArray: any = ref([])
const machineIDs: any = ref([])
const machineIDs2: any = ref([])
const machineIDs3: any = ref([])
const machineS: any = ref([])
const machineS2: any = ref([])

const machineSObj: any = ref()

const jtdtBiao: any = ref([])
const jtewmxBiao: any = ref([])
const ssmxBiao: any = ref([])
let tempIds: any
const macChanges = (e: any) => {
  console.log('手动排产勾选改变macChanges', e)
  let objArrays: any = []
  machinesIdArray.value = e
  e.forEach((item: any) => {
    tempMachines.forEach((item2: any) => {
      if (item == item2.id) {
        objArrays.push(item2.machineCode)
      }
    })
  })
  tempIds = objArrays
  console.log('tempIds', tempIds)
  if (tabKey.value != 888 && tempIds.length) {
    console.log('进来了')
    const updateRows = dataListssz.value.map((item: any) => {
      return {
        ...item,
        alreadySchedulingNum: item.orderWeight,
        onceSchedulingNum: 0,
      }
    })
    gridOption5.value.setRowData(updateRows)
  } else {
    const updateRows = dataListssz.value.map((item: any) => {
      return {
        ...item,
        alreadySchedulingNum: 0,
        onceSchedulingNum: item.orderWeight,
      }
    })
    gridOption5.value.setRowData(updateRows)
  }
}

const machinesIdArray2 = ref([])

const macChangess = (e: any) => {
  console.log('手动排产勾选改变macChangess', e)
  // let machinesIdArrays = e.map((es) => Number(es.split('/')[0]))
  tempIds = e.map((item: any) => item.split('/')[1])
  // post({
  //   url: 'planSingle/planSchedul/getScheduleInfoByMachine',
  //   data: e.map((res) => {
  //     return {
  //       id: Number(res.split('/')[0]),
  //       machineCode: res.split('/')[1],
  //     }
  //   }),
  // }).then((res: any) => {
  //   if (res.code == 200) {
  //     jtdtBiao.value = res.data
  //     ArrayList2.value.forEach((item: any) => {
  //       item.detail.layout.forEach((items: any) => {
  //         if (machinesIdArrays.includes(items.id)) {
  //           items.isBooval = true
  //         } else {
  //           items.isBooval = false
  //         }
  //       })
  //     })
  //   } else {
  //     Message.error(res.message)
  //   }
  // })
}
// const showMachineList = ref<any>([])
const storeyStors = (val: any) => {
  if (val == '') {
    //当楼层框不选择时 默认显示所有数据
    // showMachineList.value.push(...pageData.clothListr.floorName)
    let objMachineS: any = []
    machineS2.value.forEach((o: any) => {
      if (!machinesIdArray.value.includes(o.id)) {
        objMachineS.push(o)
      }
    })
    machineS.value = JSON.parse(JSON.stringify(objMachineS))
    machineS.value.unshift(...machineIDs.value)
  } else {
    //先清空上一次选择的楼层数据
    // showMachineList.value = []
    // showMachineList.value.push(val)
    let objMachineS: any = []
    machineS2.value.forEach((res: any) => {
      if (!machinesIdArray.value.includes(res.id)) {
        if (res.areaName == val) {
          objMachineS.push(res)
        }
      }
    })
    machineS.value = JSON.parse(JSON.stringify(objMachineS))
    machineS.value.unshift(...machineIDs.value)
  }
}

const ArrayJTDT: any = ref([])
const ArrayJTRWMX: any = ref([])
const ArrayJTSS: any = ref([])

const loading: any = ref(false)

const pcTitels: any = ref('')
const yesAndNoP: any = ref(false)

const tititles = ref('')
const schedulingType = ref('')
const paic = async () => {
  tititles.value = '自动排产'
  yesAndNoP.value = true
  pcTitels.value = '自动排产'
  schedulingType.value = '自动排产'
  pageData.showAdd = false
  machinesIdArray.value = []
  machineIDs.value = []
  machineS.value = []
  machineS2.value = []
  changeIds.value = []
  changeIdArry = []
  selectedRowKeys.value = []
  jtdtBiao.value = []
  jtewmxBiao.value = []
  ssmxBiao.value = []
  selectedKeys2.value = []
  objArray.value = []
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  if (gridOption.value.getSelectedRows().length > 1) {
    Message.error('只能勾选一条')
    return
  }
  await lc(gridOption.value.getSelectedRows()[0].firm)
  //设置css变量 挂载在html上
  const t: any = document.querySelector('html')
  t.style.setProperty('--paichan-drawer', '550px')
  t.style.setProperty('--drawer-tabs-content', '650px')
  //获取机台明细表格数据
  selectMxAll(gridOption.value.getSelectedRows()[0].outSouringCompanyId)
  //先把所有楼层页签的loading设置为true
  pageData.clothListr.forEach((item: any) => {
    item.loadingState = true
  })
  //获取第一个楼层的机台数据
  await getAllMachinesData([pageData.clothListr[0].floorName])
  pageData.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  loading.value = true
  // showMachineList.value = pageData.clothListr.floorName
  let firm = ''
  let planOrderId = ''
  let planOrderCode = ''
  let items: any
  table.dataList.forEach((item) => {
    if (
      item.id ==
      gridOption.value.getSelectedRows().map((o: any) => {
        return o.id
      })[0]
    ) {
      items = item
      firm = item.firm
      planOrderId = item.planOrderId
      planOrderCode = item.planOrderCode
      dataListss.schedulCode = item.schedulCode
      dataListss.computerTime = item.computerTime
      dataListss.applyMachine = item.applyMachine
      dataListss.firm = item.firm
      queryData.storey = item.storey
      dataListss.defaultNum = item.defaultNum
      dataListss.planOrderId = item.planOrderId
      dataListss.planOrderCode = item.planOrderCode
    }
  })
  const res: any = await post({
    url: 'planSingle/planSchedul/redisOut',
    data: [planOrderCode],
  })
  if (res.code == 200) {
    post({
      url: 'planSingle/planSchedulDetail/getList',
      data: {
        id: Number(
          gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          })
        ),
        firm,
        planOrderId,
        planOrderCode,
        applyMachine: dataListss.applyMachine,
        storey: queryData.storey,
      },
    }).then((resq: any) => {
      if (resq.code == 200) {
        macNum.value = resq.data.machineNum
        dataListssz.value = [resq.data[0]]
        // dataListssz.value[0]['planOrderCode'] = planOrderCode
        dataListssz.value[0]['greyId'] = resq.data[0].greyId
        dataListsss.value = resq.data.planSchedulLooms
        post({
          url: 'planSingle/planSchedul/getAutomaticInfo',
        }).then((resw: any) => {
          if (resw.code == 200) {
            dataListss.schedulCode = resw.data.schedulCode
          }
        })

        post({
          url: '/planSingle/planSchedul/getAutoScheduleInfo',
          data: items,
        }).then(async (rese: any) => {
          if (rese.code == 200) {
            let jitai: any
            trialMachines = JSON.parse(JSON.stringify(rese.data.machineData))
            machineS.value = JSON.parse(JSON.stringify(rese.data.machineData))
            machineS2.value = JSON.parse(JSON.stringify(rese.data.machineData))
            machineIDs2.value = []
            machineIDs3.value = []
            machineIDs.value = []
            machinesIdArray.value = []
            for (let i = 0; i < rese.data.machineNum; i++) {
              machineIDs.value.push(rese.data.machineData[i])
              machineIDs2.value.push(JSON.parse(JSON.stringify(rese.data.machineData[i])))
              machinesIdArray.value.push(rese.data.machineData[i].id)
            }
            if (machinesIdArray.value.length) {
              //如果有默认勾选的机台 要更新表格
              //已排产量=指令重量 未排产量=0
              dataListssz.value = dataListssz.value.map((item: any) => {
                return {
                  ...item,
                  alreadySchedulingNum: item.orderWeight,
                  onceSchedulingNum: 0,
                }
              })
            } else {
              //如果没有默认勾选的机台 要更新表格
              //已排产量=0 未排产量=指令重量
              dataListssz.value = dataListssz.value.map((item: any) => {
                return {
                  ...item,
                  alreadySchedulingNum: 0,
                  onceSchedulingNum: item.orderWeight,
                }
              })
            }
            jitai = machineS.value.slice(rese.data.machineNum)
            machineSObj.value = {}
            jitai.forEach((o: any) => {
              if (!Object.keys(machineSObj.value).includes(o.areaName)) {
                machineSObj.value[o.areaName] = []
                machineSObj.value[o.areaName].push(o)
              } else {
                machineSObj.value[o.areaName].push(o)
              }
            })
            post({
              url: '/planSingle/planSchedul/getScheduleInfoByMachine',
              data: machineIDs.value,
            }).then((resz: any) => {
              if (resz.code == 200) {
                jtdtBiao.value = resz.data
                loading.value = false
                pageData.showAdd = true
                visible1.value = true
                pageData.refreshStr = pageData.refreshList[0]
                isYupai.value = '排产'
                nextTick(async () => {
                  if (ArrayList.value[0] && ArrayList.value[0].detail.form.width) {
                    instance.refs[
                      'gridlayoutRef' + pageData.clothListr[0].floorName
                    ][0].$el.style.width = `${ArrayList.value[0].detail.form.width *
                    ArrayList.value[0].detail.form.longs +
                    (ArrayList.value[0].detail.form.longs + 1) * 10
                    }px`
                  }
                  for (let i = 1; i < pageData.clothListr.length; i++) {
                    if (tititles.value != '自动排产' || !pageData.showAdd) return
                    await getAllMachinesData([pageData.clothListr[i].floorName])
                  }
                })
              } else {
                yesAndNoP.value = false
                clearInterval(isS)
                post({
                  url: 'planSingle/planSchedul/upRedis',
                })
                loading.value = false
                Message.error(resz.message)
              }
            })
            // pageData.showAdd = true
            // isYupai.value = '排产'
          } else {
            yesAndNoP.value = false
            clearInterval(isS)
            post({
              url: 'planSingle/planSchedul/upRedis',
            })
            loading.value = false
            Message.error(rese.message)
          }
        })
        // } else {
        //     Message.error('还未预排')
        // }
      } else {
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        loading.value = false
        Message.error(resq.message)
      }
    })
  } else {
    yesAndNoP.value = false
    clearInterval(isS)
    post({
      url: 'planSingle/planSchedul/upRedis',
    })
    loading.value = false
    Message.error(res.message)
  }
  // isDeFou(firm, planOrderId, Number(selectedRowKeys.value), planOrderCode, dataListss.applyMachine, dataListss.storey)
}

//手动排产
let tempMachines: any
let trialMachines: any = [] //试算时勾选机台筛选
const paics = async () => {
  tititles.value = '手动排产'
  yesAndNoP.value = true
  pcTitels.value = '手动排产'
  schedulingType.value = '手动排产'
  pageData.showAdd = false
  machinesIdArray.value = []
  machineIDs.value = []
  machineS.value = []
  machineS2.value = []
  changeIds.value = []
  changeIdArry = []
  selectedRowKeys.value = []
  jtdtBiao.value = []
  jtewmxBiao.value = []
  ssmxBiao.value = []
  selectedKeys2.value = []
  objArray.value = []
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  if (gridOption.value.getSelectedRows().length > 1) {
    Message.error('只能勾选一条')
    return
  }
  await lc(gridOption.value.getSelectedRows()[0].firm)
  //设置css变量 挂载在html上
  const t: any = document.querySelector('html')
  t.style.setProperty('--paichan-drawer', '550px')
  t.style.setProperty('--drawer-tabs-content', '650px')
  //获取机台明细表格数据
  selectMxAll(gridOption.value.getSelectedRows()[0].outSouringCompanyId)
  //先把所有楼层页签的loading设置为true
  pageData.clothListr.forEach((item: any) => {
    item.loadingState = true
  })
  //获取第一个楼层的机台数据
  await getAllMachinesData([pageData.clothListr[0].floorName])
  pageData.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  loading.value = true
  // showMachineList.value = [...pageData.clothListr.floorName]
  let firm = ''
  let planOrderId = ''
  let planOrderCode = ''
  let items: any
  table.dataList.forEach((item) => {
    if (
      item.id ==
      gridOption.value.getSelectedRows().map((o: any) => {
        return o.id
      })[0]
    ) {
      items = item
      firm = item.firm
      planOrderId = item.planOrderId
      planOrderCode = item.planOrderCode
      dataListss.schedulCode = item.schedulCode
      dataListss.computerTime = item.computerTime
      dataListss.applyMachine = item.applyMachine
      dataListss.firm = item.firm
      queryData.storey = item.storey
      dataListss.defaultNum = item.defaultNum
      dataListss.planOrderId = item.planOrderId
      dataListss.planOrderCode = item.planOrderCode
    }
  })
  const res: any = await post({
    url: 'planSingle/planSchedul/redisOut',
    data: [planOrderCode],
  })
  if (res.code == 200) {
    post({
      url: 'planSingle/planSchedulDetail/getList',
      data: {
        id: Number(
          gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          })
        ),
        firm,
        planOrderId,
        planOrderCode,
        applyMachine: dataListss.applyMachine,
        storey: queryData.storey,
      },
    }).then((resq: any) => {
      if (resq.code == 200) {
        macNum.value = resq.data.machineNum
        dataListssz.value = [resq.data[0]]
        dataListssz.value[0]['planOrderCode'] = planOrderCode
        dataListssz.value[0]['greyId'] = resq.data[0].greyId
        dataListssz.value[0]['alreadySchedulingNum'] = 0
        dataListssz.value[0]['onceSchedulingNum'] = resq.data[0].orderWeight
        dataListsss.value = resq.data.planSchedulLooms
        post({
          url: 'planSingle/planSchedul/getAutomaticInfo',
        }).then((resw: any) => {
          if (resw.code == 200) {
            dataListss.schedulCode = resw.data.schedulCode
          }
        })

        post({
          url: '/planSingle/planSchedul/getAutoScheduleInfo',
          data: {
            ...items,
            cccccState: 'cccccState',
          },
        }).then((rese: any) => {
          if (rese.code == 200) {
            let jitai: any
            trialMachines = JSON.parse(JSON.stringify(rese.data.machineData))
            tempMachines = JSON.parse(JSON.stringify(rese.data.machineData))
            machineS.value = JSON.parse(JSON.stringify(rese.data.machineData))
            machineS2.value = JSON.parse(JSON.stringify(rese.data.machineData))
            machineIDs2.value = []
            machineIDs3.value = []
            machineIDs.value = []
            machinesIdArray.value = []
            jitai = machineS.value
            machineSObj.value = {}
            jitai.forEach((o: any) => {
              if (!Object.keys(machineSObj.value).includes(o.areaName)) {
                machineSObj.value[o.areaName] = []
                machineSObj.value[o.areaName].push(o)
              } else {
                machineSObj.value[o.areaName].push(o)
              }
            })
            loading.value = false
            visible1.value = true
            pageData.refreshStr = pageData.refreshList[0]
            pageData.showAdd = true
            isYupai.value = '排产'
            nextTick(async () => {
              if (ArrayList.value[0] && ArrayList.value[0].detail.form.width) {
                instance.refs[
                  'gridlayoutRef' + pageData.clothListr[0].floorName
                ][0].$el.style.width = `${ArrayList.value[0].detail.form.width * ArrayList.value[0].detail.form.longs +
                (ArrayList.value[0].detail.form.longs + 1) * 10
                }px`
              }
              for (let i = 1; i < pageData.clothListr.length; i++) {
                if (tititles.value != '手动排产' || !pageData.showAdd) return
                await getAllMachinesData([pageData.clothListr[i].floorName])
              }
            })
            isS = setInterval(() => {
              post({
                url: 'planSingle/planSchedul/redisOut',
                data: [planOrderCode],
              })
            }, 50000)
            // pageData.showAdd = true
            // isYupai.value = '排产'
          } else {
            yesAndNoP.value = false
            clearInterval(isS)
            post({
              url: 'planSingle/planSchedul/upRedis',
            })
            loading.value = false
            Message.error(rese.message)
          }
        })
        // } else {
        //     Message.error('还未预排')
        // }
      } else {
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        loading.value = false
        Message.error(resq.message)
      }
    })
  } else {
    yesAndNoP.value = false
    clearInterval(isS)
    post({
      url: 'planSingle/planSchedul/upRedis',
    })
    loading.value = false
    Message.error(res.message)
  }
}

const exports = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  } else {
    //将表头拼接出来
    let head =
      '<th>织布单号</th><th>客户</th><th>坯布编号</th><th>坯布名称</th><th>面料种类</th><th>下单重量</th><th>计划状态</th><th>下单时间</th><th>计划单状态</th>'
    //拿到当前表格数据与勾选的行做筛选

    let nowRow = table.dataList.filter(function (o) {
      return (
        gridOption.value
          .getSelectedRows()
          .map((o: any) => {
            return o.id
          })
          .indexOf(o['id']) !== -1
      )
    })
    let body = ''
    nowRow.forEach(function (o) {
      body += '<tr><td>' + o['planOrderCode'] + '</td>'
      body += '<td>' + o['customName'] + '</td>'
      body += '<td>' + o['greyCode'] + '</td>'
      body += '<td>' + o['greyName'] + '</td>'
      body += '<td>' + o['fabricType'] + '</td>'
      body += '<td>' + o['orderWeight'] + '</td>'
      body += '<td>' + (o['planState'] == 0 ? '自行生产' : '') + '</td>'
      body += '<td>' + o['examineTime'] + '</td>'
      body +=
        '<td>' +
        (o['planOrderState'] == 0 ? '正常' : o['planOrderState'] == 1 ? '急' : '紧急') +
        '</td>'
      body += '</tr>'
    })
    tableToXlsx(head, '计划单排产-未排产', body)
  }
}

function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  document.removeChild(a)
}

const tableColumns = useTableColumn([
  // {
  //     title: "排产号",
  //     key: "schedulCode",
  //     dataIndex: "schedulCode",
  //     width: 150,
  // },
  {
    title: '公司',
    key: 'outSouringCompany',
    dataIndex: 'outSouringCompany',
    width: 150,
  },
  {
    title: '织布单号',
    key: 'planOrderCode',
    dataIndex: 'planOrderCode',
    width: 150,
  },
  // {
  //     title: "计划类型",
  //     key: "planType",
  //     dataIndex: "planType",
  //     width: 150,
  // },
  {
    title: '客户',
    key: 'customName',
    dataIndex: 'customName',
    width: 150,
  },
  // {
  //     title: "机台号",
  //     key: "schedulMachineCode",
  //     dataIndex: "schedulMachineCode",
  //     width: 150,
  // },
  {
    title: '坯布编号',
    key: 'greyCode',
    dataIndex: 'greyCode',
    width: 200,
  },
  {
    title: '坯布名称',
    key: 'greyName',
    dataIndex: 'greyName',
    width: 450,
  },
  // {
  //     title: "产品类别",
  //     key: "productType",
  //     dataIndex: "productType",
  //     width: 150,
  // },
  {
    title: '面料种类',
    key: 'fabricType',
    dataIndex: 'fabricType',
    width: 150,
  },
  // {
  //     title: "品牌",
  //     key: "brandName",
  //     dataIndex: "brandName",
  //     width: 150,
  //     align: 'left'
  // },
  {
    title: '下单重量',
    key: 'orderWeight',
    dataIndex: 'orderWeight',
    width: 150,
  },
  // {
  //     title: "加工单价",
  //     key: "machinPrice",
  //     dataIndex: "machinPrice",
  //     width: 150,
  // },
  // {
  //     title: "加工金额",
  //     key: "machinMoney",
  //     dataIndex: "machinMoney",
  //     width: 150,
  // },
  {
    title: '计划单状态',
    key: 'planOrderState',
    dataIndex: 'planOrderState',
    slotName: 'planOrderState',
    width: 150,
    fixed: 'right',
  },
  // {
  //     title: "订单交期",
  //     key: "orderDeliveryDate",
  //     dataIndex: "orderDeliveryDate",
  //     width: 150,
  // },
  {
    title: '计划状态',
    key: 'planState',
    dataIndex: 'planState',
    slotName: 'planState',
    width: 150,
  },
  {
    title: '下单时间',
    key: 'examineTime',
    dataIndex: 'examineTime',
    slotName: 'examineTime',
    width: 150,
  },
])

const tableColumns1: any = [
  {
    headerName: '织布单号',
    field: 'planOrderCode',
    width: 150,
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 150,
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 450,
  },
  {
    headerName: '指令重量',
    field: 'orderWeight',
    width: 150,
  },
  {
    headerName: '已排产量',
    field: 'alreadySchedulingNum',
    width: 150,
  },
  {
    headerName: '未排产量',
    field: 'onceSchedulingNum',
    width: 150,
  },
  {
    headerName: '适用机型',
    field: 'applyMachine',
    width: 150,
  },
  {
    headerName: '织单针寸数',
    field: 'workDrum',
    width: 150,
  },
  {
    headerName: '颜色',
    field: 'colorName',
    width: 150,
  },
  {
    headerName: '纱长',
    field: 'yarnLong',
    width: 150,
  },
  {
    headerName: '最晚交期',
    field: 'lastDeliveryTime',
    width: 150,
  },
]

const tableColumns2: any = [
  {
    title: '机台编号',
    key: 'machineCode',
    dataIndex: 'machineCode',
    width: 150,
  },
  {
    title: '生产单号',
    key: 'weavingCode',
    dataIndex: 'weavingCode',
    width: 150,
  },
  {
    title: '坯布编号',
    key: 'greyCode',
    dataIndex: 'greyCode',
    width: 150,
  },
  {
    title: '坯布名称',
    key: 'greyName',
    dataIndex: 'greyName',
    width: 450,
  },
  {
    title: '织单机型',
    key: 'orderMachineType',
    dataIndex: 'orderMachineType',
    width: 150,
  },
  {
    title: '织单针寸数',
    key: 'workDrum',
    dataIndex: 'workDrum',
    width: 150,
  },
  {
    title: '纱长',
    key: 'yarnLength',
    dataIndex: 'yarnLength',
    width: 150,
  },
  {
    title: '颜色',
    key: 'colorName',
    dataIndex: 'colorName',
    width: 150,
  },
  {
    title: '色号',
    key: 'colorCodes',
    dataIndex: 'colorCodes',
    width: 150,
  },
  {
    title: '客户名称',
    key: 'customName',
    dataIndex: 'customName',
    width: 150,
  },
  {
    title: '机台针寸数',
    key: 'machineWorkDrum',
    dataIndex: 'machineWorkDrum',
    width: 150,
  },
  {
    title: '主推商品号',
    key: 'productColthCode',
    dataIndex: 'productColthCode',
    width: 150,
  },
  {
    title: '机台预计完成时间',
    key: 'finishTime',
    dataIndex: 'finishTime',
    width: 150,
  },
  {
    title: '机台负荷',
    key: 'machineInfo',
    dataIndex: 'machineInfo',
    slotName: 'machineInfo',
    width: 100,
    fixed: 'right',
  },
  {
    title: '机台状态',
    key: 'machineState',
    dataIndex: 'machineState',
    slotName: 'machineState',
    width: 100,
    fixed: 'right',
  },
]
const tableColumns4: any = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: '生产序号',
    field: 'serialNum',
    width: 150,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 150,
  },
  {
    headerName: '位置号',
    field: 'area',
    width: 150,
  },
  {
    headerName: '生产单号',
    field: 'weavingCode',
    width: 150,
  },
  {
    headerName: '织布单号',
    field: 'planOrderCode',
    width: 150,
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 200,
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 450,
  },
  {
    headerName: '针寸数',
    field: 'workDrum',
    width: 120,
  },
  {
    headerName: '纱长',
    field: 'yarnLength',
    width: 120,
  },
  {
    headerName: '颜色',
    key: 'colorName',
    dataIndex: 'colorName',
    slotName: 'colorName',
    width: 120,
  },
  {
    headerName: '指令重量',
    field: 'orderWeight',
    width: 120,
  },
  {
    headerName: '分配重量',
    field: 'alreadyWeight',
    width: 120,
    // cellRenderer: {
    //   template: `
    //   <a-input-number v-model="alreadyWeight" :precision="2" class="input-demo" :min="0" :max="10000"/>
    //   `,
    //   setup(props: any) {
    //     const alreadyWeight = ref(props.params.data.alreadyWeight)
    //     return {
    //       alreadyWeight,
    //     }
    //   },
    // },
  },
  {
    headerName: '已生产重量',
    field: 'hasProductWeight',
    width: 120,
  },
  {
    headerName: '未生产重量',
    field: 'productWeight',
    width: 120,
  },
  {
    headerName: '织造交期',
    field: 'weavDeliveryDate',
    width: 120,
  },
  {
    headerName: '预计开机时间',
    field: 'pStartTime',
    width: 120,
  },
  {
    headerName: '预计完成时间',
    field: 'pEndTime',
    width: 120,
  },
  {
    headerName: '实际开机时间',
    field: 'actualStartTime',
    width: 120,
  },
  {
    headerName: '实际完成时间',
    field: 'actualEndTime',
    width: 120,
  },
  {
    headerName: '理论产量',
    field: 'theoreticalYield',
    width: 120,
  },
  {
    headerName: '暂停标识',
    field: 'stopType',
    width: 120,
  },
  {
    headerName: '插单标识',
    field: 'insertState',
    width: 120,
    pinned: 'right',
    cellRenderer: {
      template: `<a-checkbox v-model="checkBox" @change="cheChange" :disabled="rowData.serialNum==1"></a-checkbox>`,
      setup(props: any) {
        const rowData = ref(props.params.data)
        const checkBox = ref(props.params.data.insertState == 0 ? false : true)
        const cheChange = (val: any) => {
          if (val) {
            agClousData2.value.forEach((res: any, index: any) => {
              if (res.id == props.params.data.id) {
                res.insertState = 1
              }
            })
          } else {
            props.params.data.insertState = 0
          }
        }
        return {
          rowData,
          checkBox,
          cheChange,
        }
      },
    },
  },
  {
    headerName: '生产状态',
    field: 'productionState',
    width: 150,
    pinned: 'right',
    valueGetter: (params: any) => {
      return params.data.productionState == 0
        ? '等待'
        : params.data.productionState == 1
          ? '生产中'
          : '暂停'
    },
  },
  {
    headerName: '插单时间',
    field: 'insertTime',
    width: 150,
    pinned: 'right',
  },
]

const tableColumns3: any = [
  {
    headerName: '生产序号',
    field: 'serialNum',
    width: 150,
  },
  {
    headerName: '生产单号',
    field: 'weaveingCode',
    width: 150,
  },
  {
    headerName: '调机类型',
    field: 'maintainType',
    width: 150,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 150,
  },
  {
    headerName: '位置号',
    field: 'storey',
    width: 150,
  },
  {
    headerName: '织布单号',
    field: 'planOrderCode',
    width: 150,
  },
  {
    headerName: '指令重量',
    field: 'orderWeight',
    width: 150,
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 200,
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 450,
  },
  {
    headerName: '产品类别',
    field: 'productType',
    width: 150,
  },
  {
    headerName: '分配重量',
    field: 'alreadyWeight',
    width: 120,
    cellRenderer: {
      template: `
        <a-input-number v-model="state.alreadyWeight" @change="handleAlreadyWeightChange" :precision="2" class="input-demo" :min="0" :max="10000"/>
        `,
      setup(props: any) {
        const state = ref(props.params.data)
        const handleAlreadyWeightChange = (e: any) => {
          if (!e) {
            state.value.alreadyWeight = 0
          }
        }
        return {
          state,
          handleAlreadyWeightChange,
        }
      },
    },
  },
  {
    headerName: '分配匹数',
    field: 'pieceNum',
    width: 150,
  },
  {
    headerName: '预计开始时间',
    field: 'startTime',
    width: 180,
  },
  {
    headerName: '预计完成时间',
    field: 'endTime',
    width: 180,
  },
  {
    headerName: '针寸数',
    field: 'workDrum',
    width: 150,
  },
  {
    headerName: '织造交期',
    field: 'weavDeliveryDate',
    width: 150,
  },
  {
    headerName: '生产状态',
    field: 'pStart',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: ` <span>{{ b == 0 ? '等待' : '生产' }}</span>`,
      setup(props: any) {
        return {
          b: props.params.data.pStart,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '等待' : '生产'
      },
    },
  },
  {
    headerName: '状态',
    field: 'rowsState',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button size="mini" v-if="b == 0" type="outline">正常</a-button>
                   <a-button size="mini" v-if="b == 1" type="primary" status="danger">超出交期</a-button>`,
      setup(props: any) {
        return {
          b: props.params.data.rowsState,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '正常' : params.value == '1' ? '超出交期' : ''
      },
    },
  },
]

interface isDatalist {
  id: any
  schedulCode: any
  computerTime: any
  applyMachine: any
  firm: any
  storey: any
  defaultNum: any
  planOrderId: any
  planOrderCode: any
}

let dataListss = reactive<isDatalist>({
  id: '',
  schedulCode: '',
  computerTime: '',
  applyMachine: '',
  firm: '',
  storey: '',
  defaultNum: '',
  planOrderId: null,
  planOrderCode: null,
})

let dataListsss = ref<any[]>([])
const table = useTable()
const pageData = reactive<any>({
  showAdd: false,
  showAdd2: false,
  rHeight: 0,
  clothListr: [],
  pageLoading: false,
  updateTime: '',
  refreshStr: '全部',
  refreshList: [{ label: '全部', value: '全部' }],
})
function lc(firm = '') {
  return new Promise((resolve, reject) => {
    post({
      url: '/planSingle/planSchedul/getMachineAreaPara',
      data: {
        firm,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        pageData.clothListr = res.data.map((item: any) => {
          return {
            floorName: item,
            loadingState: true,
          }
        })
        tabKey.value = pageData.clothListr[0].floorName
        tabKey2.value = pageData.clothListr[0].floorName
        const formatRefreshList = res.data.map((item: any) => {
          return {
            label: item,
            value: item,
          }
        })
        pageData.refreshList.push(...formatRefreshList)
        resolve(pageData.clothListr)
      }
    })
  })
}
function getPermissionFloor() {
  return new Promise((resolve, reject) => {
    post({
      url: '/planSingle/planSchedul/getMachineAreaPara',
      data: {
        remark: 'permissionFirm',
      },
    }).then((res: any) => {
      if (res.code == 200) {
        pageData.clothListr = res.data.map((item: any) => {
          return {
            floorName: item,
            loadingState: true,
          }
        })
        tabKey.value = pageData.clothListr[0].floorName
        tabKey2.value = pageData.clothListr[0].floorName
        const formatRefreshList = res.data.map((item: any) => {
          return {
            label: item,
            value: item,
          }
        })
        pageData.refreshList.push(...formatRefreshList)
        resolve(pageData.clothListr)
      }
    })
  })
}
const storeyStor = (val: any) => {
  const resDtas = table.dataList.filter((item) => {
    return item.id == gridOption.value.getSelectedRows()[0].id
  })
  post({
    url: 'planSingle/planSchedulDetail/getList',
    data: {
      id: resDtas[0].id,
      firm: resDtas[0].firm,
      planOrderId: resDtas[0].planOrderId,
      planOrderCode: resDtas[0].planOrderCode,
      applyMachine: resDtas[0].applyMachine,
      storey: queryData.storey,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      macNum.value = res.data.machineNum
      dataListssz.value = [res.data[0]]
      dataListsss.value = res.data.planSchedulLooms
      post({
        url: 'planSingle/planSchedulDetail/getMachine',
        data: {
          id: resDtas[0].id,
          firm: resDtas[0].firm,
          planOrderId: resDtas[0].planOrderId,
          planOrderCode: resDtas[0].planOrderCode,
          applyMachine: resDtas[0].applyMachine,
          storey: queryData.storey,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          res.data.forEach((item: any) => {
            item.startDate = [item.startDate, item.endDate]
          })
          dataListsss.value.unshift(...res.data)
          if (res.data.length != 0) {
            res.data.forEach((item: any) => {
              changeIds.value.unshift(item.machineId)
            })
          }
        }
      })
    }
  })
}
let yupaicId: any
const editHandler = (record: any) => {
  selectedRowKeys.value = [record.id]
  isYupai.value = '修改预排产'
  dataListss.schedulCode = record.schedulCode
  dataListss.computerTime = record.computerTime
  dataListss.applyMachine = record.applyMachine
  dataListss.firm = record.firm
  queryData.storey = record.storey
  dataListss.defaultNum = record.defaultNum
  dataListss.planOrderId = record.planOrderId
  dataListss.planOrderCode = record.planOrderCode
  // isDeFou(record.firm, record.planOrderId, record.id, record.planOrderCode, record.applyMachine, record.storey)
  post({
    url: 'planSingle/planSchedulDetail/getList',
    data: {
      id: Number(record.id),
      firm: record.firm,
      planOrderId: record.planOrderId,
      planOrderCode: record.planOrderCode,
      applyMachine: record.applyMachine,
      storey: record.storey,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      macNum.value = res.data.machineNum
      dataListssz.value = [res.data[0]]
      dataListsss.value = res.data.planSchedulLooms
      post({
        url: 'planSingle/planSchedulDetail/getMachine',
        data: {
          id: Number(record.id),
          firm: record.firm,
          planOrderId: record.planOrderId,
          planOrderCode: record.planOrderCode,
          applyMachine: record.applyMachine,
          storey: record.storey,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          res.data.forEach((item: any) => {
            item.startDate = [item.startDate, item.endDate]
          })
          dataListsss.value.unshift(...res.data)
          if (res.data.length != 0) {
            res.data.forEach((item: any) => {
              changeIds.value.unshift(item.machineId)
            })
          }
          pageData.showAdd = true
        }
      })
    }
  })

  yupaicId = record.id
}

let isYupai = ref()
let isS: any

let dataListssz: any = ref([])
// function isDeFou(firm: any, planOrderId: any, id: any, planOrderCode: any, applyMachine: any, storey: any) {
//     post({
//         url: "planSingle/planSchedulDetail/getList",
//         data: {
//             id,
//             firm,
//             planOrderId,
//             planOrderCode,
//             applyMachine,
//             storey,
//         },
//     }).then((res: any) => {
//         if (res.code === 200) {
//             dataListssz.value = [res.data.planSchedulDetails[0]]
//             dataListsss.value = res.data.planSchedulLooms
//             if (res.data.schedulPlanSchedulLooms.length != 0) {
//                 res.data.schedulPlanSchedulLooms.forEach((item: any) => {
//                     dataListsss.value.unshift({
//                         id: item.id,
//                         firm: item.firm,
//                         machineCode: item.machineCode,
//                         startDate: [item.startDate, item.endDate]
//                     })
//                     changeIds.value.unshift(item.id)
//                 })
//             }
//         } else {
//             Message.error(res.message)
//         }
//     })
// }

let changeIdArry: any[] = []
let changeIds = ref<any[]>([])
const changeId = (value: any) => {
  changeIds.value = value
  const taData = table.dataList.filter((item: any) => {
    return gridOption.value.getSelectedRows()[0].id == item.id
  })
  let isDataList: any = []
  value.forEach((is: any) => {
    dataListsss.value.forEach((item: any) => {
      if (is == item.machineId) {
        isDataList.push({
          createName: item.createName,
          createTime: item.createTime,
          deleteState: item.deleteState,
          endDate: item.startDate[1],
          firm: item.firm,
          id: item.id,
          machineCode: item.machineCode,
          machineId: item.machineId,
          machineName: item.machineName,
          obsoleteState: item.obsoleteState,
          planOrderCode: item.planOrderCode,
          planSchedulId: item.planSchedulId,
          remark: item.remark,
          startDate: item.startDate[0],
          storey: item.storey,
        })
      }
    })
  })
  post({
    url: 'planSingle/planSchedulDetail/schedulMachine',
    data: {
      ...taData[0],
      machine: isDataList,
    },
  }).then((res: any) => {
    const id = gridOption.value.getSelectedRows()[0].id
    if (res.code == 200) {
      post({
        url: 'planSingle/planSchedulDetail/getList',
        data: {
          id,
          firm: taData[0].firm,
          planOrderId: taData[0].planOrderId,
          planOrderCode: taData[0].planOrderCode,
          applyMachine: taData[0].applyMachine,
          storey: queryData.storey,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          macNum.value = res.data.machineNum
          dataListssz.value = [res.data.planSchedulDetails[0]]
          dataListsss.value = res.data.planSchedulLooms
          post({
            url: 'planSingle/planSchedulDetail/getMachine',
            data: {
              id: gridOption.value.getSelectedRows()[0].id,
              firm: taData[0].firm,
              planOrderId: taData[0].planOrderId,
              planOrderCode: taData[0].planOrderCode,
              applyMachine: taData[0].applyMachine,
              storey: queryData.storey,
            },
          }).then((res: any) => {
            if (res.code == 200) {
              res.data.forEach((item: any) => {
                item.startDate = [item.startDate, item.endDate]
              })
              dataListsss.value.unshift(...res.data)
              // if (res.data.length != 0) {
              //     res.data.forEach((item: any) => {
              //         changeIds.value.unshift(item.machineId)
              //     })
              // }
            }
          })
        }
      })
    } else {
      changeIds.value = []
      Message.error(res.message)
    }
  })
}

const sendOemOrder = () => {
  let ptDatas = gridOption.value.getSelectedRows()
  console.log(ptDatas[0])
  let greyCodeList = ptDatas.map((o) => {
    return o.greyCode
  })
  let greyCodeSet = new Set(greyCodeList)
  if (greyCodeList.length == 0) {
    Message.error('请选择数据！')
    return
  }
  if (greyCodeSet.size > 1) {
    Message.error('请选择相同的坯布编号')
    return
  }

  post({
    url: '/planSingle/oemOrder/createOemOrder',
    data: ptDatas,
  }).then(({ code, data }) => {
    console.log(code)
    if (code == 200) {
      Message.success('创建委外加工订单成功！')
      doRefresh()
    }
  })
}

const sideOk1 = () => {
  if (isYupai.value == '预排产') {
    let planOrderCodes: any
    table.dataList.forEach((item: any) => {
      if (item.id == gridOption.value.getSelectedRows()[0].id) {
        planOrderCodes = item.planOrderCode
      }
    })
    let ischangeIdArrys: any = []
    for (let i = 0; i < changeIds.value.length; i++) {
      dataListsss.value.forEach((item: any) => {
        if (item.machineId == changeIds.value[i]) {
          ischangeIdArrys.push({
            id: item.id,
            firm: item.firm,
            planOrderCode: planOrderCodes,
            machineCode: item.machineCode,
            startDate: item.startDate[0],
            endDate: item.startDate[1],
            storey: item.storey,
          })
        }
      })
    }
    if (ischangeIdArrys.length == 0) {
      Message.error('请选择机台')
      return
    }
    let planOrderCode
    let customName
    table.dataList.forEach((item: any) => {
      if (item.id == gridOption.value.getSelectedRows()[0].id) {
        planOrderCode = item.planOrderCode
        customName = item.customName
      }
    })
    let weaveCode
    let greyCode
    let greyName
    dataListssz.value.forEach((item: any) => {
      weaveCode = item.weaveCode
      greyCode = item.greyCode
      greyName = item.greyName
    })
    post({
      url: 'planSingle/planSchedulDetail/temporarySave',
      data: {
        id: gridOption.value.getSelectedRows()[0].id,
        planOrderCode: planOrderCode,
        customName: customName,
        schedulCode: dataListss.schedulCode,
        computerTime: dataListss.computerTime,
        applyMachine: dataListss.applyMachine,
        storey: queryData.storey,
        defaultNum: dataListss.defaultNum,
        planSchedulLooms: ischangeIdArrys,
        weaveCode,
        greyCode,
        greyName,
        schedulState: 1,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        doRefresh()
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        pageData.showAdd = false
        visible1.value = false
        selectedRowKeys.value = []
        changeIds.value = []
        dataListsss.value = []
        Message.success('保存成功')
      } else {
        Message.error(res.message)
      }
    })
  } else if (isYupai.value == '修改预排产') {
    let planOrderCodes: any
    let customNames
    table.dataList.forEach((item: any) => {
      if (item.id == yupaicId) {
        planOrderCodes = item.planOrderCode
        customNames = item.customName
      }
    })
    let ischangeIdArrys: any = []
    for (let i = 0; i < changeIds.value.length; i++) {
      dataListsss.value.forEach((item: any) => {
        if (item.machineId == changeIds.value[i]) {
          ischangeIdArrys.push({
            id: item.id,
            firm: item.firm,
            planOrderCode: planOrderCodes,
            machineCode: item.machineCode,
            startDate: item.startDate[0],
            endDate: item.startDate[1],
            storey: item.storey,
          })
        }
      })
    }
    let weaveCode
    let greyCode
    let greyName
    dataListssz.value.forEach((item: any) => {
      weaveCode = item.weaveCode
      greyCode = item.greyCode
      greyName = item.greyName
    })
    post({
      url: 'planSingle/planSchedulDetail/update',
      data: {
        id: Number(yupaicId),
        planOrderCode: planOrderCodes,
        customName: customNames,
        schedulCode: dataListss.schedulCode,
        computerTime: dataListss.computerTime,
        applyMachine: dataListss.applyMachine,
        storey: queryData.storey,
        defaultNum: dataListss.defaultNum,
        planSchedulLooms: ischangeIdArrys,
        weaveCode,
        greyCode,
        greyName,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        doRefresh()
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        pageData.showAdd = false
        visible1.value = false
        Message.success('保存成功')
        selectedRowKeys.value = []
        changeIds.value = []
        dataListsss.value = []
      } else {
        Message.error(res.message)
      }
    })
  } else if (isYupai.value == '排产') {
    let planOrderId: any
    let planOrderCodes: any
    let customNames: any
    let drawnNeedleState: any
    table.dataList.forEach((item: any) => {
      if (item.id == gridOption.value.getSelectedRows()[0].id) {
        planOrderId = item.planOrderId
          ; (customNames = item.customName), (drawnNeedleState = item.drawnNeedleState)
        planOrderCodes = item.planOrderCode
      }
    })
    let weaveCode: any
    let greyCode: any
    let greyName: any
    dataListssz.value.forEach((item: any) => {
      weaveCode = item.weaveCode
      greyCode = item.greyCode
      greyName = item.greyName
    })
    let ischangeIdArrys: any = []
    for (let i = 0; i < changeIds.value.length; i++) {
      dataListsss.value.forEach((item: any) => {
        if (item.machineId == changeIds.value[i]) {
          ischangeIdArrys.push({
            id: item.id,
            planOrderCode: planOrderCodes,
            machineCode: item.machineCode,
            startDate: item.startDate[0],
            endDate: item.startDate[1],
            weaveCode,
            greyCode,
            greyName,
            customName: customNames,
            drawnNeedleState: drawnNeedleState,
            storey: item.storey,
          })
        }
      })
    }
    post({
      url: 'planSingle/planSchedulDetail/save',
      data: {
        id: gridOption.value.getSelectedRows()[0].id,
        planOrderId,
        planOrderCode: planOrderCodes,
        planSchedulLooms: ischangeIdArrys,
        schedulCode: dataListss.schedulCode,
        weaveCode,
        greyCode,
        greyName,
        storey: queryData.storey,
        schedulState: 2,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        pageData.showAdd = false
        visible1.value = false
        doRefresh()
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        changeIds.value = []
        Message.success('订单排产')
        selectedRowKeys.value = []
      } else {
        Message.error(res.message)
      }
    })
  }
}

const sidesOks = () => {
  let objZORS = pcTitels.value == '手动排产' ? { handState: 'handState' } : {}
  // if (!yesAndNoP.value) {
  //   Message.error('无排产订单！')
  //   return
  // }
  if (ssmxBiao.value.length === 0) {
    Message.warning('请先试算')
  } else {
    fullLoading.value = true
    const saveRowData: any = []
    gridOption4.value.forEachNode((node: any) => {
      saveRowData.push(node.data)
    })

    post({
      url: '/planSingle/planSchedul/getScheduleSave',
      data: {
        ...dataListssz.value[0],
        ...dataListss,
        after: jtewmxBiao.value,
        save: saveRowData,
        ...objZORS,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        Message.success('订单排产')
        yesAndNoP.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        machinesIdArray.value = []
        machineIDs.value = []
        machineS.value = []
        machineS2.value = []
        changeIds.value = []
        changeIdArry = []
        selectedRowKeys.value = []
        pageData.showAdd = false
        visible1.value = false
        jtdtBiao.value = []
        jtewmxBiao.value = []
        ssmxBiao.value = []
        ssmxBiao2.value = []
        selectedKeys2.value = []
        objArray.value = []
        yesAndNoP.value = false
        fullLoading.value = false
        emitter.emit('bcCx')
        doRefresh()
        const machineCodes = table1Ref.value
          .getSelectedRows()
          .map((item: any) => item.machineCode)
        //排产保存后应该保留显示排产的机台列表
        post({
          url: 'product/statement/getMachineDetail',
          data: {
            page: 1,
            size: 100000,
            machineCodes,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            jtdtBiao.value = res.data
          } else {
            Message.error(res.message)
          }
        })
        // router.replace({ path: '/redirect/processrowfactory/planplant' })
      } else {
        Message.error(res.message)
      }
      fullLoading.value = false
    })
  }
}
let tempMachineCodes = ref([])
const sideNo1 = async () => {
  console.log('test', tempIds)
  tempMachineCodes.value = []
  if (machineIDs2.value.length > 0 && !tempIds) {
    tempIds = [machineIDs2.value[0].machineCode.toString()]
  }
  if ((tabKey.value == 888 || tabKey2.value == 888) && table1Ref.value.getSelectedRows().length > 0) {
    try {
      const machineCodes = table1Ref.value.getSelectedRows().map((item: any) => item.machineCode)
      if (tempIds && tempIds.length) {
        const tempIdsStr = tempIds.map((item: any) => String(item))
        machineCodes.push(...tempIdsStr)
        tempMachineCodes.value = machineCodes
      }
      const res = await post({
        url: 'product/statement/getMachineDetail',
        data: {
          page: 1,
          size: 100000,
          machineCodes,
        },
      })
      if (res.code == 200) {
        console.log('机台明细确认', res)
        jtdtBiao.value = res.data.list
        ArrayList.value.forEach((item: any) => {
          item.detail.layout.forEach((items: any) => {
            if (machineCodes.includes(items.id)) {
              items.isBooval = true
            } else {
              items.isBooval = false
            }
          })
        })
      } else {
        Message.error(res.message)
        return
      }
    } catch (e) {
      console.log(e)
    }
  } else {
    try {
      const tempIdsStr = tempIds.map((item: any) => item.toString())
      const machineCodes = tempIdsStr
      tempMachineCodes.value = machineCodes
      const res = await post({
        url: 'product/statement/getMachineDetail',
        data: {
          page: 1,
          size: 100000,
          machineCodes,
        },
      })
      if (res.code == 200) {
        console.log('其他页签', res)
        jtdtBiao.value = res.data.list
        ArrayList.value.forEach((item: any) => {
          item.detail.layout.forEach((items: any) => {
            if (machineCodes.includes(items.id)) {
              items.isBooval = true
            } else {
              items.isBooval = false
            }
          })
        })
      } else {
        Message.error(res.message)
        return
      }
    } catch (e) {
      console.log(e)
    }
  }
  pageData.showAdd = false
  pageData.showAdd2 = false
  tabKey.value = pageData.clothListr[0].floorName
  tabKey2.value = pageData.clothListr[0].floorName
  // pageData.clothListr.forEach((item: any) => (item.loadingState = false))
  pageData.clothListr = []
  tempIds = null
  if (schedulingType.value == '手动排产') {
    shiSuans()
    ArrayList.value = []
  } else if (schedulingType.value == '自动排产' || schedulingType.value == '修改机台') {
    let firm = ''
    let planOrderId = ''
    let planOrderCode = ''
    let items: any
    table.dataList.forEach((item) => {
      if (
        item.id ==
        gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        })[0]
      ) {
        items = item
        firm = item.firm
        planOrderId = item.planOrderId
        planOrderCode = item.planOrderCode
        dataListss.schedulCode = item.schedulCode
        dataListss.computerTime = item.computerTime
        dataListss.applyMachine = item.applyMachine
        dataListss.firm = item.firm
        queryData.storey = item.storey
        dataListss.defaultNum = item.defaultNum
        dataListss.planOrderId = item.planOrderId
        dataListss.planOrderCode = item.planOrderCode
      }
    })
    let tempMachineArr: any = []
    const rese = await post({
      url: '/planSingle/planSchedul/getAutoScheduleInfo',
      data: items,
    })
    console.log('rese', rese)
    tempMachineArr = rese.data.machineData
    const machineParams: any = []
    console.log('tempMachineCodes.value', tempMachineCodes.value)
    console.log('tempMachineArr', tempMachineArr)
    tempMachineCodes.value.forEach((item: any) => {
      const obj = tempMachineArr.find((item2: any) => item2.machineCode == item)
      if (obj) {
        machineParams.push(obj)
      }
    })
    post({
      url: 'planSingle/planSchedul/getScheduleCalculate',
      data: {
        ...dataListssz.value[0],
        weavDeliveryDate: dataListssz.value[0].lastDeliveryTime,
        ...dataListss,
        storey: queryData.storey,
        // machine: objArray.value
        machine: machineParams,
        taskDetail: jtewmxBiao.value,
        calculateData: ssmxBiao.value,
      },
    }).then((resb: any) => {
      if (resb.code == 200) {
        ssmxBiao.value = resb.data
        //拷贝一份出来
        initRowData = JSON.parse(JSON.stringify(resb.data))
        // gridOption4.value.setRowData(resb.data)
        ssmxBiao2.value = JSON.parse(JSON.stringify(resb.data))
        isS = setInterval(() => {
          post({
            url: 'planSingle/planSchedul/redisOut',
            data: [planOrderCode],
          })
        }, 50000)
      } else {
        loading.value = false
        clearInterval(isS)
        post({
          url: 'planSingle/planSchedul/upRedis',
        })
        Message.error(resb.message)
      }
    })
  }
  yesAndNoP.value = false
}
const visible = ref(false)
const visible1 = ref(false)
const data: any = ref([])
const paichanxq = () => {
  if (changeIds.value.length == 0) {
    Message.error('请先选择机台')
    return
  }
  let jitaiArray: any = []
  let planOrderCode
  table.dataList.forEach((item: any) => {
    if (item.id == gridOption.value.getSelectedRows()[0].id) {
      planOrderCode = item.planOrderCode
    }
  })
  changeIds.value.forEach((item: any) => {
    dataListsss.value.forEach((items: any) => {
      if (item == items.machineId) {
        // planOrderCode = items.planOrderCode
        jitaiArray.push({
          machineCode: items.machineCode,
          startDate: items.startDate[0],
          endDate: items.startDate[1],
        })
      }
    })
  })
  post({
    url: 'planSingle/machineSchedul/getData',
    data: {
      planOrderCode,
      machines: jitaiArray,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      for (let i = 0; i < res.data.days.length; i++) {
        // columns.value.splice(columns.value.length - 1, 0, {
        //     title: res.data.days[i],
        //     key: res.data.days[i],
        //     dataIndex: res.data.days[i],
        //     slotName: res.data.days[i],
        //     width: 150
        // })
        columns.value.push({
          title: res.data.days[i],
          key: res.data.days[i],
          dataIndex: res.data.days[i],
          slotName: res.data.days[i],
          width: 200,
        })
      }
      data.value = res.data.machineSchedul
      maxData.value = res.data.maxData
      orderWeight.value = res.data.orderWeight
      visible.value = true
    } else {
      Message.error(res.message)
    }
  })
  // visible.value = true
}
const maxData: any = ref()
const orderWeight: any = ref()
const handleOk = async () => {
  // selectedRowKeys
  let jihudanhao: any
  let pibubianhao: any
  let pibuName: any
  table.dataList.forEach((item: any) => {
    if (gridOption.value.getSelectedRows()[0].id == item.id) {
      jihudanhao = item.planOrderCode
      pibubianhao = item.greyCode
      pibuName = item.greyName
    }
  })
  let datas: any = []
  data.value.forEach((item: any) => {
    datas.push({
      ...item,
      planOrderCode: jihudanhao,
      greyCode: pibubianhao,
      greyName: pibuName,
    })
  })
  const res: any = await post({
    url: 'planSingle/machineSchedul/insert',
    data: datas,
  })
  if (res.code == 200) {
    Message.success(res.message)
    visible.value = false
    columns.value = [
      {
        title: '机台号',
        key: 'machineCode',
        dataIndex: 'machineCode',
        width: 150,
        fixed: 'left',
      },
      {
        title: '理论产量',
        key: 'machineTargetCapacity',
        dataIndex: 'machineTargetCapacity',
        width: 150,
        fixed: 'left',
      },
      {
        title: '极限日产能',
        key: 'maxMachineTargetCapacity',
        dataIndex: 'maxMachineTargetCapacity',
        width: 150,
        fixed: 'left',
      },
      // {
      //     title: "操作",
      //     key: "id",
      //     dataIndex: "id",
      //     slotName: "act4",
      //     width: 100,
      //     fixed: 'right'
      // },
    ]
    return true
  } else {
    Message.error(res.message)
    return false
  }
}
const handleCancel = () => {
  columns.value = [
    {
      title: '机台号',
      key: 'machineCode',
      dataIndex: 'machineCode',
      width: 150,
      fixed: 'left',
    },
    {
      title: '理论产量',
      key: 'machineTargetCapacity',
      dataIndex: 'machineTargetCapacity',
      width: 150,
      fixed: 'left',
    },
    {
      title: '极限日产能',
      key: 'maxMachineTargetCapacity',
      dataIndex: 'maxMachineTargetCapacity',
      width: 150,
      fixed: 'left',
    },
    // {
    //     title: "操作",
    //     key: "id",
    //     dataIndex: "id",
    //     slotName: "act4",
    //     width: 100,
    //     fixed: 'right'
    // },
  ]
  visible.value = false
}
const columns: any = ref([
  {
    title: '机台号',
    key: 'machineCode',
    dataIndex: 'machineCode',
    width: 150,
    fixed: 'left',
  },
  {
    title: '理论产量',
    key: 'machineTargetCapacity',
    dataIndex: 'machineTargetCapacity',
    width: 150,
    fixed: 'left',
  },
  {
    title: '极限日产能',
    key: 'maxMachineTargetCapacity',
    dataIndex: 'maxMachineTargetCapacity',
    width: 150,
    fixed: 'left',
  },
  // {
  //     title: "操作",
  //     key: "id",
  //     dataIndex: "id",
  //     slotName: "act4",
  //     width: 100,
  //     fixed: 'right'
  // },
])
let tc: any[] = tableColumns.map((o: any) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
  }
  if (o.key === 'planOrderState') {
    obj['resizable'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'right'
    obj['width'] = 120
    obj['cellRenderer'] = {
      template: ` <a-dropdown   @select="c($event)" popup-container='html'>
                <a-button @click="a" v-if="b== 2" type="primary" size="mini"
                    status="danger" shape="round">
                    紧急&nbsp
                    <icon-down />
                </a-button>
                <a-button @click="a" v-if="b == 0" type="primary" size="mini"
                    status="success" shape="round">
                    正常&nbsp
                    <icon-down />
                </a-button>
                <a-button @click="a" v-if="b == 1" status="danger" size="mini"
                    shape="round">
                    &nbsp&nbsp急&nbsp&nbsp
                    <icon-down />
                </a-button>
                <template #content>
                    <a-doption>紧急</a-doption>
                    <a-doption>急</a-doption>
                    <a-doption>正常</a-doption>
                </template >

            </a-dropdown>`,
      setup(props: any) {
        const a = () => {
          handleSelects(props.params.data)
        }
        const c = ($event: any) => {
          handleSelect($event)
        }
        return {
          b: props.params.data.planOrderState,
          a,
          c,
          d: props.params.data,
          e: props.params.data.planState,
        }
      },
    }
    obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '正常'
          : params.value == '1'
            ? '急'
            : params.value == '2'
              ? '紧急'
              : ''
      },
    }
  }
  if (o.key == 'planState') {
    obj['resizable'] = false
    obj['sortable'] = false
    obj['cellRenderer'] = {
      template: ` <span v-if="b == 0">自行生产</span>`,
      setup(props: any) {
        return {
          b: props.params.data.planState,
        }
      },
    }
    obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '自行生产' : ''
      },
    }
  }

  return obj
})

let a = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
]
tc = a.concat(tc)

let tc2: any[] = tableColumns2.map((o: any) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
  }
  if (o.key == 'pStart') {
    obj['resizable'] = false
    obj['sortable'] = false
    obj['width'] = 100
    obj['cellRenderer'] = {
      template: ` <span>{{ b == 0 ? '等待' : '生产' }}</span>`,
      setup(props: any) {
        return {
          b: props.params.data.pStart,
        }
      },
    }
    obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '等待' : '生产'
      },
    }
  }
  if (o.key == 'machineInfo') {
    obj['resizable'] = false
    obj['sortable'] = false
    obj['width'] = 100
    obj['cellRenderer'] = {
      template: ` <span>{{ showVal }}</span>`,
      setup(props: any) {
        const machineInfo = props.params.data.machineInfo
        let showVal = ref('')
        switch (machineInfo) {
          case 0:
            showVal.value = '空闲'
            break
          case 1:
            showVal.value = '正常'
            break
          case 2:
            showVal.value = '饱和'
            break
          case 3:
            showVal.value = '负荷'
            break
          case 4:
            showVal.value = '待单'
            break
        }
        return {
          showVal,
          machineInfo,
        }
      },
    }
    obj['filterParams'] = {
      valueFormatter: function (params: any) {
        const machineInfo = params.value
        let showVal = ref('')
        switch (machineInfo) {
          case 0:
            showVal.value = '空闲'
            break
          case 1:
            showVal.value = '正常'
            break
          case 2:
            showVal.value = '饱和'
            break
          case 3:
            showVal.value = '负荷'
            break
          case 4:
            showVal.value = '待单'
            break
        }
        return showVal.value
      },
    }
  }
  return obj
})

let a2 = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
]
tc2 = a2.concat(tc2)
const ssListArray: any = ref([])
const macNum: any = ref('')
const maxTimeDate = ref('')
const tiemsData = (maxTime: any) => {
  maxTimeDate.value = maxTime
  console.log(maxTimeDate.value)
}
const disbledDatas = (current: any) => {
  return dayjs(current).isBefore(dayjs(maxTimeDate.value))
}
const localeText1: any = ref(localeText)

const form: any = reactive({
  customName: '',
  planOrderCode: '',
  greyCode: '',
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}

const defaultColDefJo: any = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1,
}

const huiche = () => {
  doRefresh()
}

emitter.on('pcUpdate', async (e: any) => {
  const { code, data, message } = await post({
    url: 'planSingle/planMachineTask/getUpdateInfo',
    data: e,
  })
  if (code == 200) {
    console.log(data)
    dataListss.schedulCode = e.schedulCode
    dataListss.applyMachine = e.applyMachine
    queryData.storey = e.storey
    pageData.showAdd = true
    visible1.value = true
    isYupai.value = '修改排产'
  } else {
    Message.error(message)
  }
})
const clickRowSelectionA = () => {
  gridOption5.value.getSelectedRows()[0].id = gridOption5.value.getSelectedRows()[0].greyId
  emitter.emit('noPaiCanRowIdisXq', gridOption5.value.getSelectedRows()[0])
}
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
  saveOrUpdateGridState01('NotScheduled-1', gridOption, colState, tc)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const onColumnVisible = () => {
  saveGridState01()
}

const ArrayList = ref<any>([])
const ArrayList2 = ref<any>([])

//根据楼层获取对应机台数据
const getAllMachinesData = (storyList: any[]) => {
  return new Promise((resolve, reject) => {
    const curFloorObj = pageData.clothListr.find((item: any) => item.floorName == storyList[0])
    if (!curFloorObj) return
    curFloorObj.loadingState = true
    post({
      url: 'planSingle/machineLayout/getScheduleInfo',
      data: {
        storyList,
      },
    }).then(({ data, code }) => {
      if (code == 200) {
        data.forEach((item: any) => {
          item.detail = JSON.parse(item.detail)
        })
        ArrayList.value.push(...data)
        pageData.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        curFloorObj.loadingState = false
        console.log('loadingState', curFloorObj.loadingState)
        console.log('rrrrr', ArrayList.value)
        resolve(ArrayList.value)
      } else {
        curFloorObj.loadingState = false
        reject()
      }
    })
  })
}
const handleRefresh = async () => {
  if (pageData.refreshStr == '全部') {
    //刷新全部 重新获取所有机台数据
    ArrayList.value = []
    pageData.clothListr.forEach((item: any) => (item.loadingState = true))
    for (let i = 0; i < pageData.clothListr.length; i++) {
      if (!pageData.showAdd) return
      await getAllMachinesData([pageData.clothListr[i].floorName])
      pageData.clothListr[i].loadingState = false
    }
    const activeFloorObj = ArrayList.value.find((item: any) => item.story == tabKey.value)
    console.log('activeFloorObj', activeFloorObj)
    const width = activeFloorObj?.detail.form?.width
    console.log('width', width)
    if (width) {
      instance.refs['gridlayoutRef' + activeFloorObj.story][0].$el.style.width = `${width * activeFloorObj.detail.form.longs + (activeFloorObj.detail.form.longs + 1) * 10
        }px`
    }
  } else {
    //刷新楼层 重新获取对应机台数据
    ArrayList.value = ArrayList.value.filter((item: any) => item.story !== pageData.refreshStr)
    const curFloorObj = pageData.clothListr.find(
      (item: any) => item.floorName == pageData.refreshStr
    )
    if (curFloorObj) {
      curFloorObj.loadingState = true
      const res: any = await getAllMachinesData([pageData.refreshStr])
      curFloorObj.loadingState = false
      const { story } = res[0]
      const { form } = res[0].detail
      const { width } = form
      if (width) {
        instance.refs['gridlayoutRef' + story][0].$el.style.width = `${width * form.longs + (form.longs + 1) * 10
          }px`
      }
    }
  }
}
const handleRefresh2 = async () => {
  if (pageData.refreshStr == '全部') {
    //刷新全部 重新获取所有机台数据
    ArrayList2.value = []
    pageData.clothListr.forEach((item: any) => (item.loadingState = true))
    for (let i = 0; i < pageData.clothListr.length; i++) {
      if (!pageData.showAdd2) return
      await selectClickArrayList2([pageData.clothListr[i].floorName])
      pageData.clothListr[i].loadingState = false
    }
    const activeFloorObj = ArrayList2.value.find((item: any) => item.story == tabKey2.value)
    const width = activeFloorObj?.detail.form?.width
    if (width) {
      instance.refs['gridlayoutRef2' + activeFloorObj.story][0].$el.style.width = `${width * activeFloorObj.detail.form.longs + (activeFloorObj.detail.form.longs + 1) * 10
        }px`
    }
  } else {
    //刷新楼层 重新获取对应机台数据
    ArrayList2.value = ArrayList2.value.filter((item: any) => item.story !== pageData.refreshStr)
    const curFloorObj = pageData.clothListr.find(
      (item: any) => item.floorName == pageData.refreshStr
    )
    if (curFloorObj) {
      curFloorObj.loadingState = true
      const res: any = await selectClickArrayList2([pageData.refreshStr])
      curFloorObj.loadingState = false
      const { story } = res[0]
      const { form } = res[0].detail
      const { width } = form
      if (width) {
        instance.refs['gridlayoutRef2' + story][0].$el.style.width = `${width * form.longs + (form.longs + 1) * 10
          }px`
      }
    }
  }
}
//查看机台 根据楼层获取对应机台数据
const selectClickArrayList2 = (storyList: any[]) => {
  return new Promise((resolve, reject) => {
    const curFloorObj = pageData.clothListr.find((item: any) => item.floorName == storyList[0])
    if (!curFloorObj) return
    curFloorObj.loadingState = true
    post({
      url: 'planSingle/machineLayout/getScheduleInfo',
      data: {
        storyList,
      },
    }).then(({ data, code }) => {
      if (code == 200) {
        data.forEach((item: any) => {
          item.detail = JSON.parse(item.detail)
        })
        ArrayList2.value.push(...data)
        console.log('ArrayList2', ArrayList2.value)
        pageData.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        curFloorObj.loadingState = false
        resolve(data)
      } else {
        curFloorObj.loadingState = false
        reject()
      }
    })
  })
}

const tabKey = ref(0)
const tabKey2 = ref(0)
const tabchange = (val: any) => {
  console.log('tabchange', val)
  console.log('current', ArrayList.value)
  if (val !== '888') {
    const curObj = ArrayList.value.find((item: any) => item.story == val)
    if (curObj) {
      const width = curObj.detail.form.width
      const { form } = ArrayList.value.find((item: any) => item.story == val).detail
      if (width) {
        console.log('width', width)
        nextTick(() => {
          setTimeout(() => {
            instance.refs['gridlayoutRef' + val][0].$el.style.width = `${width * form.longs + (form.longs + 1) * 10
              }px`
          }, 100)
        })
      }
    }
    tabKey.value = val
    pageData.refreshStr = val
  }
  if (val == 888) {
    selectMxAll(gridOption.value.getSelectedRows()[0].outSouringCompanyId)
    tabKey.value = val
    nextTick(() => {
      console.log('ArrayListMacAll', ArrayListMacAll.value)
      table1Ref.value.setdataListIterface(ArrayListMacAll.value)
    })
  }
}
const tabchange2 = (val: any) => {
  const curObj = ArrayList2.value.find((item: any) => item.story == val)
  if (curObj) {
    const width = curObj.detail.form.width
    const { form } = ArrayList2.value.find((item: any) => item.story == val).detail
    if (width) {
      console.log('width', width)
      console.log('aaa', 'gridlayoutRef2' + val)

      nextTick(() => {
        setTimeout(() => {
          console.log('bbb', instance.refs)
          instance.refs['gridlayoutRef2' + val][0].$el.style.width = `${width * form.longs + (form.longs + 1) * 10
            }px`
        }, 100)
      })
    }
  }
  tabKey2.value = val
  pageData.refreshStr = val
  if (val == 888) {
    tabKey2.value = val
    nextTick(() => {
      table1Ref.value.setdataListIterface(ArrayListMacAll.value)
    })
  }
}
const getColor = (text: any, type: any) => {
  let color = ''
  // console.log(type)
  if (text == '机台') {
    if (type == 0) color = '#9fa2a8'
    if (type == 1) color = '#ccc'
    if (type == 2) color = '#ebf13fe1'
    if (type == 3) color = '#c1c460e1'
    if (type == 4) color = '#1c9a13'
    if (type == 5) color = '#2786cf'
    if (type == 6) color = '#cf2762'
    if (type == 7) color = '#c127cf'
    if (!type && type != 0) color = 'green'
  }
  if (text == '其他') color = '#c9bbbb'
  if (text == '通道') color = 'rgb(243,217,11)'
  return color
}

const getEdit = () => { }

// watch(() => machinesIdArray.value, () => {
//     ArrayList.value.forEach((item: any) => {
//         item.detail.layout.forEach((items: any) => {
//             if (machinesIdArray.value.includes(items.id)) {
//                 items.isBooval = true
//             } else {
//                 items.isBooval = false
//             }
//         })
//     })
// })

const visibleSelectAll: any = ref(false)

const selectClickAll = () => {
  ArrayList.value = []
  ArrayList2.value = []
  getAllMachinesData(pageData.clothListr.map((item: any) => item.floorName))
  visibleSelectAll.value = true
}
const ArrayListMacAll = ref([])

//获取机台明细表格数据
const selectMxAll = (firmId = '') => {
  post({
    url: 'product/statement/getMachineDetail',
    data: {
      // planOrderCode: gridOption.value.getSelectedRows()[0]?.planOrderCode,
      page: 1,
      size: 100000,
      firmId,
    },
  }).then(({ data }) => {
    ArrayListMacAll.value = data.list
    tempMachines = data.list
  })
}

const loadings = ref(false)
let itmes: any = null
const LCQuery = async () => {
  // if (!yesAndNoP.value) {
  //   Message.error('无排产订单！')
  //   return
  // }
  if (ssmxBiao.value.length == 0) {
    Message.error('请先进行手动/自动排产再进行修改机台操作！')
    return
  }
  await lc(ssmxBiao.value[0].firm)
  //设置css变量 挂载在html上
  const t: any = document.querySelector('html')
  t.style.setProperty('--paichan-drawer', '550px')
  t.style.setProperty('--drawer-tabs-content', '650px')
  //获取第一个楼层的机台数据
  await getAllMachinesData([pageData.clothListr[0].floorName])
  tititles.value = '修改机台'
  loadings.value = true
  clearTimeout(itmes)
  if (machinesIdArray.value.length > 0) {
    const updateRows = dataListssz.value.map((item: any) => {
      return {
        ...item,
        alreadySchedulingNum: item.orderWeight,
        onceSchedulingNum: 0,
      }
    })
    setTimeout(() => {
      nextTick(() => {
        gridOption5.value.setRowData(updateRows)
        let yourColumnDefs = gridOption5.value.getColumnDefs();
        let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
        if (rowIndexColumn) {
          rowIndexColumn.headerName = updateRows.length;
          gridOption5.value.setColumnDefs(yourColumnDefs);
        }
      })
    }, 2000)
  } else {
    const updateRows = dataListssz.value.map((item: any) => {
      return {
        ...item,
        alreadySchedulingNum: 0,
        onceSchedulingNum: item.orderWeight,
      }
    })
    setTimeout(() => {
      nextTick(() => {
        gridOption5.value.setRowData(updateRows)
        let yourColumnDefs = gridOption5.value.getColumnDefs();
        let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
        if (rowIndexColumn) {
          rowIndexColumn.headerName = updateRows.length;
          gridOption5.value.setColumnDefs(yourColumnDefs);
        }
      })
    }, 2000)
  }
  itmes = setTimeout(() => {
    pageData.showAdd = true
    selectMxAll(ssmxBiao.value[0].firmId)
    nextTick(async () => {
      if (ArrayList.value[0] && ArrayList.value[0].detail.form.width) {
        instance.refs['gridlayoutRef' + 0][0].$el.style.width = `${ArrayList.value[0].detail.form.width * ArrayList.value[0].detail.form.longs +
          (ArrayList.value[0].detail.form.longs + 1) * 10
          }px`
      }
      for (let i = 1; i < pageData.clothListr.length; i++) {
        if (tititles.value != '修改机台' || !pageData.showAdd) return
        await getAllMachinesData([pageData.clothListr[i].floorName])
      }
    })
    setTimeout(() => {
      loadings.value = false
      if (!pageData.showAdd) {
        Message.error('请勿连续点击,等待加载完成!!!')
      }
    }, 1000)
  }, 1000)
}
//查看机台按钮
const LCQuerys = async () => {
  if (yesAndNoP.value) {
    Message.error('存在未排完订单,请排完后再做操作！')
    return
  }
  schedulingType.value = '查看机台'
  //设置css变量 挂载在html上
  const t: any = document.querySelector('html')
  t.style.setProperty('--paichan-drawer', '640px')
  t.style.setProperty('--drawer-tabs-content', '700px')
  await getPermissionFloor()
  //查询机台明细
  selectMxAll('')
  //根据楼层获取查看机台弹窗对应楼层数据
  await selectClickArrayList2([pageData.clothListr[0].floorName])
  loadings.value = true
  clearTimeout(itmes)
  itmes = setTimeout(() => {
    pageData.showAdd2 = true
    nextTick(async () => {
      if (ArrayList2.value[0] && ArrayList2.value[0].detail.form.width) {
        instance.refs[
          'gridlayoutRef2' + pageData.clothListr[0].floorName
        ][0].$el.style.width = `${ArrayList2.value[0].detail.form.width * ArrayList2.value[0].detail.form.longs +
        (ArrayList2.value[0].detail.form.longs + 1) * 10
        }px`
      }
      for (let i = 1; i < pageData.clothListr.length; i++) {
        if (!pageData.showAdd2) return
        await selectClickArrayList2([pageData.clothListr[i].floorName])
      }
    })
    setTimeout(() => {
      loadings.value = false
      if (!pageData.showAdd2) {
        Message.error('请勿连续点击,等待加载完成!!!')
      }
    }, 1000)
  }, 2000)
}

const visiblezz = ref(false)

const ztClick = () => {
  visiblezz.value = true
}

const tjdd = () => {
  post({
    url: 'planSingle/planMachineTask/updateDate',
    data: {
      id: gridOption3.value.getSelectedRows()[0].id,
      stopType: '停机等待',
    },
  }).then(({ code, message }) => {
    if (code == 200) {
      iiooss()
      visiblezz.value = false
      Message.success(message)
    } else {
      Message.error(message)
    }
  })
}

const ztzzxyd = () => {
  post({
    url: 'planSingle/planMachineTask/updateDate',
    data: {
      id: gridOption3.value.getSelectedRows()[0].id,
      stopType: '暂停转做下单',
    },
  }).then(({ code, message }) => {
    if (code == 200) {
      iiooss()
      visiblezz.value = false
      Message.success(message)
    } else {
      Message.error(message)
    }
  })
}

function iiooss() {
  post({
    url: 'planSingle/planSchedul/getScheduleInfoByMachineAll',
    data: gridOption2.value.getSelectedRows(),
  }).then((res: any) => {
    if (res.code == 200) {
      jtewmxBiao.value = res.data
    } else {
      Message.error(res.message)
    }
  })
}

const titels = ref('')

const zjtClick = () => {
  titels.value = '转机台详情'
  renderZjtData()
}

const zjtClicks = () => {
  titels.value = '增加机台详情'
  selectJT()
}

const dblclicksShowA2 = ref(false)
const tcA2DataList = ref([])
const renderZjtData = () => {
  if (gridOption3.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  } else if (gridOption3.value.getSelectedRows().length > 1) {
    Message.error('只能选择一条数据')
    return
  }
  post({
    url: 'product/statement/getMachineDetail',
    data: {
      page: 1,
      size: 100000,
      noState: 100,
      planOrderCode: gridOption3.value.getSelectedRows()[0].planOrderCode,
    },
  }).then(({ code, message, data }) => {
    if (code == 200) {
      tcA2DataList.value = data.list
      pageConfig.zjtTotal = data.total
      dblclicksShowA2.value = true
    } else {
      Message.error(message)
    }
  })
}
const handleZjtPageChange = (val: any) => {
  pageConfig.zjtPage = val
  renderZjtData()
}
const zjtChange = (val: any) => {
  pageConfig.zjtSize = val
  renderZjtData()
}
//增加机台获取数据函数
function selectJT() {
  if (gridOption3.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  if (gridOption3.value.getSelectedRows().length > 1) {
    Message.error('只能勾选一条数据')
    return
  }
  const { id, planOrderCode, machineCode } = gridOption3.value.getSelectedRows()[0]
  post({
    url: 'planSingle/planMachineTask/getPageInfo',
    data: {
      page: 1,
      size: 100000,
      productionStates: [2],
      id,
      planOrderCode,
      // machineCode,
    },
  }).then(({ code, message, data }) => {
    if (code == 200) {
      dblclicksShowA2.value = true
      nextTick(() => {
        table2Ref.value.setdataListIterface(data.list)
      })
    } else {
      Message.error(message)
    }
  })
}
const saveZjtLoading = ref(false)
const saveZjt = async () => {
  if (titels.value == '转机台详情') {
    try {
      if (gridOptionA2.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      if (gridOptionA2.value.getSelectedRows().length > 1) {
        Message.error('只能选择一条数据')
        return
      }
      const id = gridOption3.value.getSelectedRows()[0].id
      post({
        url: 'planSingle/planMachineTask/getMessageByAdj',
        data: {
          id,
        },
      }).then((res) => {
        if (res.code == 200) {
          zJt()
        } else {
          switchMachineSaveModalMessage.value = res.message
          switchMachineSaveModal.value = true
        }
      })
    } catch (e) {
      console.log(e)
    }
  } else {
    //增加机台详情确认
    if (table2Ref.value.getSelectedRows().length == 0) {
      Message.error('请先勾选')
      return
    }
    try {
      const res = await post({
        url: 'planSingle/planOrderChange/checkSubmitInfo',
        data: table2Ref.value.getSelectedRows(),
      })
      if (res.code == 200) {
        zjJt()
      } else {
        addMachineMessageboxMsg.value = res.message
        addMachineMessageVisible.value = true
      }
    } catch (e) {
      console.log(e)
    }
  }
}
const handleSwitchMachineSaveOk = () => {
  zJt()
}
const handleSwitchMachineSaveCancel = () => {
  switchMachineSaveModal.value = false
}
async function zJt() {
  try {
    const outTabelData = gridOption3.value.getSelectedRows()
    const inTabelData = gridOptionA2.value.getSelectedRows()
    fullLoading1.value = true
    const { code, message } = await post({
      url: 'planSingle/planSchedul/saveChangeMachineByOrder',
      data: {
        id: outTabelData[0].id,
        old: outTabelData[0].planOrderCode,
        newMachineCode: inTabelData[0].machineCode,
      },
    })
    if (code == 200) {
      iiooss()
      dblclicksShowA2.value = false
      switchMachineSaveModal.value = false
      Message.success(message)
    } else {
      Message.error(message)
    }
  } catch (e) {
    console.log(e)
  } finally {
    fullLoading1.value = false
  }
}
function zjJt() {
  saveZjtLoading.value = true
  const { planOrderCode } = table2Ref.value.getSelectedRows()[0]
  const list = table2Ref.value.getSelectedRows()
  post({
    url: 'planSingle/planSchedul/saveMachineByOrder',
    data: {
      planOrderCode,
      list,
    },
  }).then(({ code, message, data }) => {
    if (code == 200) {
      iiooss()
      addMachineMessageVisible.value = false
      dblclicksShowA2.value = false
      saveZjtLoading.value = false
      Message.success(message)
    } else {
      Message.error(message)
    }
  })
}

const gridOptionA2 = ref()
const gridReadyA2 = (params: any) => {
  gridOptionA2.value = params.api
}

let tcA2: any[] = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  {
    headerName: '公司',
    field: 'firm',
    pinned: 'fixed',
  },
  {
    headerName: '机台编号',
    field: 'machineCode',
    pinned: 'fixed',
  },
  {
    headerName: '机台类型',
    field: 'machineTypeName',
    pinned: 'fixed',
  },
  {
    headerName: '位置号',
    field: 'coordinate',
    pinned: 'fixed',
  },
  {
    headerName: '机台状态',
    field: 'machineState',
    pinned: 'fixed',
  },
  {
    headerName: '客户名称',
    field: 'customName',
    pinned: 'fixed',
  },
  {
    headerName: '订单针筒',
    field: 'workDrum',
    pinned: 'fixed',
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    pinned: 'fixed',
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    pinned: 'fixed',
  },
]

const rowClickeds = async () => {
  if (gridOption3.value.getSelectedRows().length < 1) {
    Message.error('请勾选数据')
    return
  }
  if (gridOption3.value.getSelectedRows().length == 1) {
    try {
      const params = gridOption3.value.getSelectedRows()[0]
      const { code, data } = await post({
        url: 'planSingle/planMachineTask/getPmtInChange',
        data: {
          machineCode: params.machineCode,
        },
      })
      if (code == 200) {
        data.forEach((res: any, index: any) => {
          res.serialNum = index + 1
        })
        agClousData2.value = data
        dblclicksShowA1.value = true
      } else {
        Message.error('查询失败')
      }
    } catch (e) {
      console.log(e)
    }
  }
}

const dblclicksShowA1 = ref(false)

const agClousData2 = ref([])

const gridReady2AFs = ref()
const gridReady2AF = (params: any) => {
  gridReady2AFs.value = params.api
}

const agClous2 = [
  {
    field: '',
    rowDrag: (params: any) => {
      // return !(params.data.serialNum == 1 || params.data.insertState == 1)
      if (params.data.serialNum == 1 && params.data.productionState == 1) return false
      if (
        params.data.serialNum == 1 &&
        params.data.productionState != 1 &&
        (params.data.adjustmentState == 2 ||
          params.data.adjustmentState == 3 ||
          params.data.adjustmentState == 4)
      )
        return false
      return true
    },
    width: 50,
  },
  {
    headerName: '机台号',
    field: 'machineCode',
    width: 100,
  },
  {
    headerName: '生产序号',
    field: 'serialNum',
    width: 120,
  },
  {
    headerName: '生产单号',
    field: 'weavingCode',
    width: 150,
  },
  {
    headerName: '生产状态',
    field: 'productionState',
    width: 150,
    valueGetter: (params: any) => {
      return params.data.productionState == 0
        ? '等待'
        : params.data.productionState == 1
          ? '生产中'
          : params.data.productionState == 3
            ? '暂停'
            : ''
    },
  },
  {
    headerName: '调机单状态',
    field: 'adjustmentState',
    width: 150,
    valueFormatter: (params: any) => {
      return params.value == 0
        ? '未派工'
        : params.value == 1
          ? '已派工'
          : params.value == 2
            ? '已开始调机'
            : params.value == 3
              ? '调机回馈录入'
              : params.value == 4
                ? '已结束调机'
                : ''
    },
  },
  {
    headerName: '插单标识',
    field: 'insertState',
    width: 120,
    pinned: 'right',
    cellRenderer: {
      template: `<a-checkbox v-model="checkBox" @change="cheChange" :disabled="rowData.serialNum==1"></a-checkbox>`,
      setup(props: any) {
        const rowData = ref(props.params.data)
        const checkBox = ref(props.params.data.insertState == 0 ? false : true)
        const cheChange = (val: any) => {
          // let index1 = 0
          if (val) {
            agClousData2.value.forEach((res: any, index: any) => {
              if (res.id == props.params.data.id) {
                // index1 = index
                res.insertState = 1
                // let currentDate = new Date()
                // let year = currentDate.getFullYear()
                // let month = currentDate.getMonth() + 1 // 月份从0开始，所以要加1
                // let day = currentDate.getDate()
                // let hours = currentDate.getHours()
                // let minutes = currentDate.getMinutes()
                // let seconds = currentDate.getSeconds()
                // res.insertTime = `${year} -${month} -${day} ${hours}:${minutes}:${seconds}`
              }
            })
            // let copyA = JSON.parse(JSON.stringify(agClousData2.value[index1].serialNum))
            // agClousData2.value[index1].serialNum = JSON.parse(
            //   JSON.stringify(agClousData2.value[1].serialNum)
            // )
            // agClousData2.value[1].serialNum = copyA
            // agClousData2.value.sort((a, b) => a.serialNum - b.serialNum)
            // setTimeout(() => {
            //   gridReady2AFs.value.setRowData(agClousData2.value)
            // }, 0)
          } else {
            props.params.data.insertState = 0
          }
        }
        return {
          rowData,
          checkBox,
          cheChange,
        }
      },
    },
  },
  {
    headerName: '插单时间',
    field: 'insertTime',
    width: 150,
    pinned: 'right',
  },
]
//插单按钮
const insertOrder = () => {
  const insertData = agClousData2.value.filter((item: any) => item.insertState === 1)
  const unInsertData = agClousData2.value.filter((item: any) => item.insertState === 0)
  const resultData = [agClousData2.value[0], ...insertData, ...unInsertData.slice(1)]
  let currentDate = new Date()
  let year = currentDate.getFullYear()
  let month = currentDate.getMonth() + 1 // 月份从0开始，所以要加1
  let day = currentDate.getDate()
  let hours = currentDate.getHours()
  let minutes = currentDate.getMinutes()
  let seconds = currentDate.getSeconds()
  resultData.forEach((item: any, index: any) => {
    item.serialNum = index + 1
    if (item.insertState === 1) {
      item.insertTime = `${year} -${month} -${day} ${hours}:${minutes}:${seconds}`
    }
  })
  agClousData2.value = resultData
}
const rowDragEnd = (event: any) => {
  const sortedData: any = []
  for (let i = 0; i < event.api.getDisplayedRowCount(); i++) {
    const rowNode = event.api.getDisplayedRowAtIndex(i)
    sortedData.push(rowNode.data)
  }
  console.log(sortedData[0].serialNum)

  if (sortedData[0].serialNum > 1) {
    setTimeout(() => {
      gridReady2AFs.value.setRowData(agClousData2.value)
    }, 0)
  } else if (agClousData2.value[1].insertState == 1 && sortedData[1].serialNum > 2) {
    setTimeout(() => {
      gridReady2AFs.value.setRowData(agClousData2.value)
    }, 0)
  } else {
    sortedData.forEach((res: any, index: any) => {
      res.serialNum = index + 1
    })
    setTimeout(() => {
      gridReady2AFs.value.setRowData(sortedData)
      agClousData2.value = sortedData
    }, 0)
  }
}

const defaultColDef2: any = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1,
}

const zjtbc = () => {
  post({
    url: 'planSingle/planMachineTask/updatePmtSerNum',
    data: agClousData2.value,
  }).then(({ code }) => {
    if (code == 200) {
      Message.success('保存成功')
      agClousData2.value = []
      dblclicksShowA1.value = false
      iiooss()
    }
  })
}

const sideNo1s = () => {
  clearInterval(isS)
  post({
    url: 'planSingle/planSchedul/upRedis',
  })
  machinesIdArray.value = []
  machinesIdArray2.value = []
  machineIDs.value = []
  machineS.value = []
  machineS2.value = []
  changeIds.value = []
  changeIdArry = []
  selectedRowKeys.value = []
  pageData.showAdd = false
  visible1.value = false
  jtdtBiao.value = []
  jtewmxBiao.value = []
  ssmxBiao.value = []
  selectedKeys2.value = []
  objArray.value = []
  yesAndNoP.value = false
}
</script>
<style lang="less" scoped>
.insert-order-box {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-center: center;

  .el-button {
    margin: 0 10px 10px 0;
  }
}

.song-9 {
  font-family: '宋体', 'SimSun', sans-serif;
  font-size: 9px;
  width: 100%;
  /* 设置盒子的宽度 */
  height: calc(100% / 5);
  /* 设置盒子的高度 */
  display: flex;
  /* 让盒子显示为弹性盒子 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  overflow: hidden;
  /* 超出隐藏 */
  white-space: nowrap;
  /* 不换行 */
  text-overflow: ellipsis;
  /* 超出显示省略号 */
}

.evenRowStyl {
  background-color: red !important;
}

.cssToolbar {
  margin-bottom: 10px;
  text-align: right;
}

.iscon {
  width: 100%;
  height: 100%;
  display: flex;
}

.iscontent {
  width: 100%;
  height: 100%;
}

.iscontent2 {
  width: 100%;
  height: 100%;

  .iscontent21 {
    padding: 20px;
    height: 100%;

    .divs {
      margin-top: 10px;
      height: 30%;
      border-bottom: 1px dashed #ccc;
    }

    .divs2 {
      position: relative;

      span {
        position: absolute;
        right: 50px;
        top: 30px;
      }
    }
  }
}

.bg-content {
  width: 100%;
  height: 10%;
  // zoom: 1;
  margin-bottom: 2px;

  :deep(.arco-checkbox-group) {
    .bg-contentA {
      width: 100%;
      border-top: 1px dashed #ccc !important;
      // justify-content: space-around !important;
      display: flex !important;
      align-items: center;
      // flex-wrap: wrap !important;
      text-align: center !important;
      height: 120px;
      margin-bottom: 2px;
      zoom: 1;
      // margin-left: 60px;
    }
  }

  div {
    margin-top: 10px;
    margin-left: 5px;
    text-align: left;

    div {
      width: 150px;
      height: 50px;
      text-align: center;
      border: 1px solid #ccc;
    }
  }
}

:deep(.arco-checkbox-label) {
  margin-top: 15px;
}

.huClass {
  background-color: #a4ffcb;
}

.lvClass {
  background-color: #fffdbb;
}

.wxClass {
  background-color: red;
}

#aTag {
  height: 80px;
  width: 60px;
  text-align: center;
  position: sticky;
  left: 1px;
  z-index: 1888;
}

.jitaipaic {
  display: flex;

  .jitaipaic1 {
    margin-left: 50px;
  }
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.layoutBox {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.layoutBoxs {
  width: 100%;
  height: 100%;
}

.grid_cals2 {
  width: 100%;
  // overflow: auto;
  display: -webkit-box;
  -webkit-overflow-scrolling: touch;
  height: var(--paichan-drawer) !important;
}

.grid-item {
  // border-top: 2px solid rgba(1, 153, 209, 0.5);
  border: #999 dashed 1px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.clmodule {
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // align-self: center;
  height: 100%;
  color: #000;
  font-weight: 600;
}

.arco-checkbox-group {
  display: inline !important;
}

.borderClass {
  border: 8px solid red;
}

:deep(.is-leaf) {
  background-color: #dde2eb !important;
  border-right: 1px solid #ccc !important;
}

:deep(.cell) {
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
}

:deep(.el-scrollbar__bar) {
  width: 12px !important;
}

:deep(.arco-btn-size-mini) {
  height: 24px;
  padding: 0 5px;
  font-size: 12px;
  border-radius: var(--border-radius-small);
}

:deep(.switch-dialog) {
  z-index: 2000 !important;
}

// :deep(.arco-tabs) {
//   overflow: auto !important;
// }
:deep(.arco-tabs-content) {
  height: var(--drawer-tabs-content) !important;
}

:deep(.arco-tabs-content-list) {
  height: 100% !important;
}
</style>
